基于注解的注入,又称自动装配。
Spring提供的装配标签:@Autowired与@Qualifier
让Spring将属性需要的对象,从Spring容器中找出来,并注入给该属性。
· 配置
在测试环境中,可以不做任何配置,直接使用@Autowired。(在Spring3.0前必须配置)
非测试环境中,需进行配置:
1、新增命名空间,配置schema位置。
2、在<beans>中添加一行代码。
<context:annotation-config />
· 阅读源代码
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.
*/
boolean required() default true;
}
可看出,其使用目标为:构造器,字段,方法,注解。
· 一些细节
1、标注在构造器时,可以注入多个对象。
@Autowired
public BeanObject(OtherBean other, OtherBean other2) {
// do work
}
2、标注在字段(实例成员变量)时,可以不提供setter方法。
3、标注在方法时,该方法为属性的setter方法。
4、使用@Autowired标签可以注入Spring内置的重要对象。如BeanFactory,ApplicationContext。
5、默认情况下@Autowired标签必须要能找到对应的对象,否则报错。
可以配置@Aurowired的required属性值为false来避免该问题。即表示该属性不是必须的。
基于@Autowired注入属性的流程:
1、首先,根据依赖对象的类型找。找不到则报错,找到唯一的匹配类型,则注入。
找到多个匹配类型时,则按id、name找。
(当@Autowired标注的是接口对象时,若该接口有唯一实现,则找该实现类型。
若没有实现,则报错。若有多个实现,则按id、name查找)
2、按照id、name找。找不到,就报错。
可以用配置@Qualifier的value属性,根据value的值找匹配的id、name。
JavaEE提供的装配标签:@Resource
· 配置
配置同@Autowired。
<context:annotation-config>既引入了@Autowired标签的解析器,也引入了@Resource的解析器。
· 阅读部分源代码
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
/**
* The JNDI name of the resource. For field annotations,
* the default is the field name. For method annotations,
* the default is the JavaBeans property name corresponding
* to the method. For class annotations, there is no default
* and this must be specified.
*/
String name() default "";
// 其余代码略
}
@Resource提供了name属性,相当于@Qualifier的name属性。
使用方法基本同@Autowried和@Qualifier。
@Autowired与@Resource
1、@Autowired:Spring定义的标签,所以可能不太稳定,并且对象和spring框架关联(Spring对代码有侵入);
2、@Resouce:是J2EE的规范,所以稳定,在J2EE规范容器中也能正常使用。