【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方法上。
相关推荐
UrbanJazzerati几秒前
当网页翻页时,页码藏在哪里?——一次对分页机制的解密之旅
后端·面试
用户4490412095562 分钟前
一次生产环境下的Redis连接耗尽问题排查与解决全过程
后端
Tapir6 分钟前
被 Karpathy 下场推荐的 NanoClaw 是什么来头
前端·后端·github
带刺的坐椅9 分钟前
SolonCode v0.0.20 发布 - 编程智能体(新增子代理和浏览器能力)
java·ai·agent·solon·solon-ai·claude-code·openclaw
ssshooter1 小时前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust
代码搬运媛1 小时前
Go 语言通道 (Channel) 深度用法讲解及实战
后端·go
会员源码网1 小时前
数字格式化陷阱:如何优雅处理 NumberFormatException
java
程序员爱钓鱼2 小时前
Go生成唯一ID的标准方案:github.com/google/uuid使用详解
后端·google·go
Moment2 小时前
MinIO已死,MinIO万岁
前端·后端·github
无双_Joney2 小时前
心路散文 - 转职遇到AI浪潮,AIGC时刻人的价值是什么?
前端·后端·架构