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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值