【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方法上。
相关推荐
一只大袋鼠几秒前
JavaWeb ——Cookie 对象
java·servlet·javaweb·cookie·小蛋糕
wooyoo几秒前
花了一周 vibe 了一个 OpenClaw 的 Agent 市场,聊聊过程中踩的坑
前端·后端·agent
树獭叔叔35 分钟前
文本Embedding模型演进:从Encoder-only到LLM-based的技术变革
后端·aigc·openai
游离态指针40 分钟前
首字节响应 0ms?我用 1000 行代码驯服了 Spring AI Agent 的“不确定性”
后端
、BeYourself1 小时前
Scala 字面量
开发语言·后端·scala
zdl6861 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
程序员buddha1 小时前
Java面试八股文高级篇
java·jvm·面试
Memory_荒年1 小时前
Gateway:微服务前台的“瑞士军刀”小姐姐
后端
yc_xym1 小时前
SpringAI快速入门
java·springai·deepseek