3.基于注解的配置
声明bean类或者组件有两种方式:
1、采用 XML 来描述一个 bean 连线
2、注解方式--Spring是能够自动扫描,检测和预定义的项目包并实例化bean
1、首先要在spring.xml中添加:
<!-- 注解方式 -->
<context:component-scan base-package="com.wm.spring.Annotation"/>
当<context:annotation-config/>配置后,您就可以开始注释代码表明,Spring自动扫码base-package下的包,自动连线的值到属性,方法和构造函数。
但是要在spring.xml文件中引入context规范约束
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
2、在bean类或者组件中添加 注解
控制层:
@Controller
public class StudentController {
@Autowired
private StudentService service ;
public void doTestAnnotation(){
service.doTestAnnotation();
System.out.println("StudentController ......");
}
}
服务层:
@Service
public class StudentService {
@Autowired
private StudentDao dao ;
public void doTestAnnotation(){
dao.doTestAnnotation();
System.out.println("StudentService .......");
}
}
DAO层:@Repository
public class StudentDao {
public void doTestAnnotation(){
System.out.println("StudentDao .......");
}
}
测试:
@Test
public void TestAnnotation(){
System.out.println("注解方式:");
StudentController sc = (StudentController)ac.getBean("studentController");
sc.doTestAnnotation();
}
结果:
信息: Loading XML bean definitions from class path resource [spring.xml]
注解方式:
StudentDao .......
StudentService .......
StudentController ......
3、常用注解
- @Component – 指示自动扫描组件。
- @Repository – 表示在持久层DAO组件。
- @Service – 表示在业务层服务组件。
- @Controller – 表示在表示层控制器组件。
- @Autowired -表示自动匹配(按照类名)