基于注解的装配
在spring框架中,尽管使用XML配置文件可以很简单的装配Bean,但如果应用中有大量的Bean需要装配,会导致XML配置文件过于庞大,不方便以后的升级与维护,因此更多的时候推荐开发者使用注解(annotation)的方式去装配Bean。
(1)@Component
该注解是一个泛化的概念,仅仅表示一个组件对象(Bean)可以作用在任何层次上。
- 下面通过一个实例来讲解@Component。
1)创建Bean的实现类
package annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 相当于@Component
* 或Component(vaule="annotationUser)
* annotationUser为Bean的id 默认为首字母小写的类名
*/
@Component
public class AnnotationUser {
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
@Value("chenheng") //只注入了简单的值,对于复杂的注入目前使用该方法还解决不了
private String uname;
}
2)配置注解
现在有了Bean的实现类,但还不能进行测试,因为Spring容器并不知道去哪里扫描Bean对象,需要在配置文件中配置注解。
annotationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" 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/beans
http://www.springframework.org/schema/beans http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--使用context命名空间 通过spring扫描指定包annotation及其子包下
所有Bean的实现类 进行注解解析-->
<context:component-scan base-package="annotation"/>
</beans>
3)测试Bean实例
package test;
import annotation.AnnotationUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAnnotation {
public static void main(String[] args) {
ApplicationContext appCon=new ClassPathXmlApplicationContext("annotationContext.xml");
AnnotationUser au= (AnnotationUser) appCon.getBean("annotationUser");
System.out.println(au.getUname());
}
}
- 2.@Repository
该注解用于将数据访问层(DAO层)的类标识为Bean,即注解数据访问层Bean,其功能与@Compontent相同
- 3.@Service
该注解用于标注一个业务逻辑组件类(Service层),其功能与@Component。
- 4.@Controller
该注解用于标注一个控制器组件类(SpringMVC的Controller),其功能与@Component相同
5.AutoWired
该注解可以对类成员变量,方法以及构造方法进行标注,完成自动装配的工作。通过使用@Autowired来消除setter和getter方法。默认按照Bean的类型进行装配。
6.@Resource
该注解与@Autowired的功能一样,区别在于该注解默认是按照名称来装配注入的,只有当找不到与名称匹配的Bean时才会按照类型来装配注入;而@Autowired默认按照Bean的类型来装配,如果想按照名称来装配注入,则需要和@Qualifer注解一起使用
@Resource注解由两个属性----name和type。name属性指定Bean实例名称,即按照名称来装配注入;type属性指定Bean的类型,即按照Bean的类型进行装配。
7@Qualifier
该注解与@Autowired注解配合使用,当@Autowired注解需要按照名称来装配注入时需要和该注解一起使用,Bean的实例名称由@Qualifier注解参数指定。