一、@Resource的理解
@Resource在bean注入的時候使用,@Resource所屬包其實不是spring,而是javax.annotation.Resource,只不過spring支持該注解
@Resource里有name,lookup,type,authenticationType,shareable,mappedName,description這幾個屬性
具體看源碼結構截圖
0、可以直接在要注入的屬性上這樣寫
@Resource
private User user;
不管配置文件里有沒有寫id或name,都能識別到,默認應該是根據類class來識別的。
1、name
當spring的xml配置文件中的bean配置了name或id時,它都可以識別到,也就是如果<bean id="user_id" name="user_name" class="xxx.xxx.xxx"></bean>,那么可以在要注入的屬性上加@Resource(name="user_id")或者@Resource(name="user_name")都可以
2、lookup
3、type
Class type() default java.lang.Object.class;這個是源碼,默認值是Object.class,那就一目了然了,無需多說了
4、authenticationType
AuthenticationType authenticationType() default AuthenticationType.CONTAINER;這個是源碼,AuthenticationType這是個枚舉類,有兩個屬性CONTAINER,APPLICATION。
暫時沒搞懂這倆有啥區別,有知道的麻煩告知
5、shareable
指示此組件和其他組件之間是否可以共享該資源。這可以指定代表任何支持類型的連接工廠的資源,並且不能為其他類型的資源指定。它是一個布爾型,默認是true
6、mappedName
7、description
當然,spring的注入不光是可以屬性注入,也可以set方法和構造函數注入,也就是說
@Resource
public void setUser(User user) {
this.user = user;
}
二、@Autowired的理解
@Autowired是屬於spring的注解,它所在的包org.springframework.beans.factory.annotation,它是按byType注入的,默認是要依賴的對象必須存在,看源碼就可以理解,boolean required() default true;可以看到默認值是true,如果需要允許依賴對象是null,那就@Autowired(required=false)就可以了。
如果我們想@Autowired按名稱裝配,可以結合@Qualifier注解一起使用
@Autowired
@Qualifier("user")
private User user;