@Autowired和@Resource的区别
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就会根据名称进行匹配。
一开始看到这句话的时候有点怀疑,因为和我的认知是有点出入。印象中使用@Autowired的时候,假如存在多个实现类,如果不通过@Qualifier 指定,那么会注入失败。但刚刚经过试验,官方文档说的是对的。那么目前这个时候@Autowired和@Resource的区别就比较少了。
但两者之间的出发点还是不一样。@Resource是通过名字注入,类型注入是fallback。而@Autowired是通过类型注入,名字注入是fallback。这个体现下面的声明:
@Resource Object userService
可以注入userService bean id/name为userService的实现类,而@Autowired不行。
官方的这段话:
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的基础上进行过滤的。
以上是 @Autowired和@Resource的区别 的全部内容, 来源链接: utcz.com/z/513307.html