【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方法上。
相关推荐
间彧7 分钟前
什么是蓝绿部署
后端
爷_32 分钟前
Golang: sqlc 和 goose 最佳实践
后端·go·全栈
听风吟丶40 分钟前
MyBatis 深度实战:从基础映射到企业级性能优化
java·tomcat
仟濹1 小时前
【Java 基础】面向对象 - 继承
java·开发语言
6***83051 小时前
微服务搭建----springboot接入Nacos2.x
java
万少1 小时前
我是如何使用 Trae IDE 完成《流碧卡片》项目的完整记录
前端·后端·ai编程
ituff1 小时前
微软认证考试又免费了
后端·python·flask
倔强的石头_2 小时前
openGauss赋能智能客服:AI时代的企业服务变革
后端
likuolei2 小时前
XML 元素 vs. 属性
xml·java·开发语言
自不量力的A同学2 小时前
Spring Boot 4.0.0 正式发布
java·spring boot·后端