@Autowired和@Resource区别的新理解

在官方文档中同时也看到这么一段话:java

Letting qualifier values select against target bean names, within the type-matching candidates, does not require a @Qualifier annotation at the injection point. If there is no other resolution indicator (such as a qualifier or a primary marker), for a non-unique dependency situation, Spring matches the injection point name (that is, the field name or parameter name) against the target bean names and choose the same-named candidate, if any.

意思就是说,若是使用@Autowired进行注入,若是没有使用@Qualifier以及@Primary等注解明显标志须要注入的依赖,那么Spring就会根据名称进行匹配。express

一开始看到这句话的时候有点怀疑,由于和个人认知是有点出入。印象中使用@Autowired的时候,假如存在多个实现类,若是不经过@Qualifier 指定,那么会注入失败。但刚刚通过试验,官方文档说的是对的。那么目前这个时候@Autowired和@Resource的区别就比较少了。ide

但二者之间的出发点仍是不同。@Resource是经过名字注入,类型注入是fallback。而@Autowired是经过类型注入,名字注入是fallback。这个体现下面的声明:ui

@Resource Object userService

能够注入userService bean id/name为userService的实现类,而@Autowired不行。code

官方的这段话:component

That said, if you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if it is capable of selecting by bean name among type-matching candidates. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process. @Autowired has rather different semantics: After selecting candidate beans by type, the specified String qualifier value is considered within those type-selected candidates only (for example, matching an account qualifier against beans marked with the same qualifier label).

也说明若是但愿经过惟一的beanid注入,建议使用@Resource进行注入。虽然@Autowired可以实现差很少的功能,可是@Autowired仍是机遇type-match的基础上进行过滤的。ci

下面继续罗列一下@Resource和@Autowired的区别:
一、@Autowired能够做用在construct,field,setter方法(能够有多个参数,而且参数上可使用@Qualifies进行标注),而@Resource只可使用在field,setter方法上(只能是单个单数的setter方法)文档

二、对于self reference上的处理方式不同。(目前尚未搞明白)get

相关文章
相关标签/搜索