一、注解
使用注解之前要开启自动扫描功能
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <context:component-scan base-package="SpringAnnotationBll,SpringAnnotationDal" /> </beans>
二、结构代码
三、常用注解
@Service用于标注业务层组件、
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件。
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Scope用于指定scope作用域的(用在类上)
四、实例
4.1、dao层代码
package SpringAnnotationDal; public interface SpringAnnotationDal { public abstract void add(); }
package SpringAnnotationDal; import org.springframework.stereotype.Repository; @Repository public class SpringAnnotationDalBean implements SpringAnnotationDal { /* (non-Javadoc) * @see SpringAnnotationDal.SpringAnnotationDal#add() */ public void add() { System.out.print("add..."); } }
4.2、service层代码
package SpringAnnotationBll; public interface SpringAnnotationBll { public abstract void add(); }
package SpringAnnotationBll; import org.springframework.stereotype.Service; import SpringAnnotationDal.SpringAnnotationDal; @Service public class SpringAnnotaionBllBean implements SpringAnnotationBll { private SpringAnnotationDal springAnnotationDal; public SpringAnnotationDal getSpringAnnotationDal() { return springAnnotationDal; } public void setSpringAnnotationDal(SpringAnnotationDal springAnnotationDal) { this.springAnnotationDal = springAnnotationDal; } public void add() { System.out.print("add..."); } }
4.3、调用
package test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import SpringAnnotationBll.SpringAnnotationBll; import spring.testServiceBean; public class cservlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); SpringAnnotationBll services=(SpringAnnotationBll)context.getBean("springAnnotaionBllBean"); services.add(); } }
五、结果
原文地址:https://www.cnblogs.com/WJ--NET/p/8303946.html
时间: 2024-10-13 06:45:38