Spring Boot中@Autowired和@Resource的区别

介绍

@Autowired

使用Idea写以下形式的代码

@Autowire
private JdbcTemplate jdbcTemplate;

就会出现一下形式的警告

Field injection is not recommended Inspection info: Spring Team recommends: “Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies”

虽然说基本不影响什么,但是还是要关注以下的
这段警告是Spring官方的建议,翻译过来就是:

属性字段注入的方式不推荐,检查到的问题是:Spring团队建议:“始终在bean中使用基于构造函数的依赖项注入,始终对强制性依赖项使用断言”

@Resource

Spring官方文档中曾说过这句话

@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.If no name is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.

翻译:@Resource,它在语义上被定义为通过其唯一的名称来标识特定的目标组件,其中声明的类型与匹配过程无关。如果没有明确指定名称,则默认名称是从字段名称或设置方法(get、set方法)派生的。 如果用在字段上,则采用字段名称; 如果用在在setter方法,它采用其属性名称(例如getProperty()方法,取property做为属性名称)。

并且还提供了一个实例

public class MovieRecommender {
   
    @Resource
    private CustomerPreferenceDao customerPreferenceDao;
    @Resource
    private ApplicationContext context;

    public MovieRecommender() {
   
    }
    ...
}

Thus in the following example, the customerPreferenceDao field first looks for a bean named customerPreferenceDao, then falls back to a primary type match for the type CustomerPreferenceDao. The “context” field is injected based on the known resolvable dependency type ApplicationContext.

解释:customerPreferenceDao字段首先查找名字为customerPreferenceDao的bean,如果没找到该类,则以CustomerPreferenceDao类型进行匹配。

比较@Autowired和@Resource

@Resource

  • @Resource默认按byName自动注入。
  • 既不指定name属性,也不指定type属性,则自动按byName方式进行查找。如果没有找到符合的bean,则回退为一个原始类型进行进行查找,如果找到就注入。
  • 只指定了@Resource注解的name,则按name后的名字去bean元素里查找有与之相等的name属性的bean。
  • 只指定@Resource注解的type属性,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常。
  • 如果未明确指定名称,则默认名称是从字段名称或setter方法派生的。如果是字段,则使用字段名称。在使用setter方法的情况下,它采用bean属性名称。以下示例将名为beanmovieFinder的setter方法注入。

官方建议

  • 基于字段注入
public class MovieRecommender {
   

    @Resource
    private CustomerPreferenceDao customerPreferenceDao;

    @Resource
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值