【Spring】聊一聊Autowired和Resource

聊一聊Autowired和Resource

对于日常使用来说,在Spring容器中,两个注解的功能基本是等价的,他们都可以将bean注入到对应的field中。

他们之间主要有以下几个关键的区别:
来源不同
  1. @Autowired 是 Spring 框架提供的注解,用于处理自动装配的过程。
  2. @Resource 来自 Java EE 规范(JSR-250),是 Javax 框架的一部分,在 Spring 中同样支持该注解进行依赖注入。同样所有的IOC容器都会支持这个注解。假如系统容器从Spring迁移到其他IOC容器中,是不需要修改代码的。
注入方式不同
  1. Autowired在获取bean的时候,先是byType的方式,再是byName的方式。如果有多个相同类型的Bean时,如果没有指定限定条件@Qualifier或者属性名匹配将会抛出异常,举个例子:

    java 复制代码
    @Component
    public class AutowiredAndResource {
        /** 异常:多个相同类型的Bean,然后byName仍然无法匹配 */
        @Autowired
        private Fruit fruit;
        /** 正常:多个相同类型的Bean,配合@Qualifier注解byName匹配 */
        @Autowired
        @Qualifier("apple")
        private Fruit fruitApple;
        /** 正常:多个相同类型的Bean,通过属性名byName匹配 */
        @Autowired
        private Fruit orange;
    }
    
    interface Fruit{}
    @Component
    class Apple implements Fruit{}
    @Component
    class Orange implements Fruit{}
  2. Resource在获取bean的时候,和Autowired相反,先是byName方式,然后再是byType方式。举个例子:

    java 复制代码
    @Component
    public class AutowiredAndResource {
    		/** 异常:byName无法匹配,byType匹配到多个相同类型的Bean */
        @Resource
        private Fruit fruit;
        /** 正常:通过name指定要匹配的对象名称 */
        @Resource(name = "apple")
        private Fruit fruitApple;
        /** 正常:通过byType注入 */
        @Resource(type = Apple.class)
        private Fruit fruitApple2;
        /** 正常:先byName直接找到了orange,然后注入 */
        @Resource
        private Fruit orange;
    }
    
    interface Fruit{}
    @Component
    class Apple implements Fruit{}
    @Component
    class Orange implements Fruit{}
作用域不同
  1. Autowired可以作用在构造器,字段,setter方法上。
  2. Resource 只可以使用在字段,setter方法上。
相关推荐
WiChP6 小时前
【V0.1B5】从零开始的2D游戏引擎开发之路
java·服务器·数据库
cch89186 小时前
汇编与Java:底层与高层的编程对决
java·开发语言·汇编
荒川之神7 小时前
拉链表概念与基本设计
java·开发语言·数据库
cch89187 小时前
汇编与Go:底层到高层的编程差异
java·汇编·golang
chushiyunen7 小时前
python中的@Property和@Setter
java·开发语言·python
禾小西7 小时前
Java中使用正则表达式核心解析
java·python·正则表达式
2401_895521347 小时前
SpringBoot Maven快速上手
spring boot·后端·maven
yoyo_zzm7 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
APIshop8 小时前
Java获取京东商品详情接口(item_get)实战指南
java·linux·数据库