【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方法上。
相关推荐
Yeats_Liao15 分钟前
时序数据库系列(八):InfluxDB配合Grafana可视化
数据库·后端·grafana·时序数据库
任子菲阳32 分钟前
学Java第四十三天——Map双列集合
java·开发语言
zeijiershuai1 小时前
Java 会话技术、Cookie、JWT令牌、过滤器Filter、拦截器Interceptor
java·开发语言
fury_1231 小时前
tsfile.raw提示
java·前端·javascript
q***7481 小时前
Spring Boot环境配置
java·spring boot·后端
superlls1 小时前
(Spring)Spring Boot 自动装配原理总结
java·spring boot·spring
郝开1 小时前
Spring Boot 2.7.18(最终 2.x 系列版本)3 - 枚举规范定义:定义基础枚举接口;定义枚举工具类;示例枚举
spring boot·后端·python·枚举·enum
q***7481 小时前
Spring Boot 3.x 系列【3】Spring Initializr快速创建Spring Boot项目
spring boot·后端·spring
q***18061 小时前
十八,Spring Boot 整合 MyBatis-Plus 的详细配置
spring boot·后端·mybatis
m0_736927042 小时前
2025高频Java后端场景题汇总(全年汇总版)
java·开发语言·经验分享·后端·面试·职场和发展·跳槽