基於註解的注入,又稱自動裝配。
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規範容器中也能正常使用。