美文网首页
@Autowired和@Resource的区别

@Autowired和@Resource的区别

作者: everxu | 来源:发表于2020-02-09 22:37 被阅读0次

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

    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的基础上进行过滤的。

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

    2、对于self reference上的处理方式不一样。(目前还没有搞明白)

    相关文章

      网友评论

          本文标题:@Autowired和@Resource的区别

          本文链接:https://www.haomeiwen.com/subject/vqkoxhtx.html