zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[email protected]@Autowired理解详解编程语言

编程语言 详解 理解 &# email 160 protected Autowired
2023-06-13 09:20:45 时间
[email protected]

@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 "__yjs_email__" href="http://blog.ytso.com/cdn-cgi/l/email-protection" data-yjsemail="e1086342055869046e4e055a44047d49094760075249046444067b6504507f07614605596b046b41a1b384928e94938284">[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;
}

 

[email protected]

@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;

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15735.html

cjavaxml