java shareable_spring中@Resource和@Autowired理解详解_编程语言_IT虾米网
@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時,它都可以識別到,也就是如果,[email?protected](name="user_id")[email?protected](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是屬于spring的注解,它所在的包org.springframework.beans.factory.annotation,它是按byType注入的,默認是要依賴的對象必須存在,看源碼就可以理解,boolean required() default true;可以看到默認值是true,如果需要允許依賴對象是null,[email?protected](required=false)就可以了。
[email?protected],[email?protected]
@Autowired
@Qualifier("user")
private User user;
總結
以上是生活随笔為你收集整理的java shareable_spring中@Resource和@Autowired理解详解_编程语言_IT虾米网的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 淤泥管道机器人_丛台区设备管道清洗超高效
- 下一篇: C语言 fopen 函数 - C语言零基