@Autowired 和 @Resource 区别的补充说明与示例

参考

补充说明与总结

  • @Resource 有两个属性 name 和 type。
    • 可以指定特定的子类实现
  • @Autowired 没有属性指定。
    • 如果涉及到 type 无法辨别注入对象时,需要依赖 @Qualifier@Primary 注解来修饰
  • 但两者都可以通过 name 或 type 容错识别

示例

java 复制代码
    @Resource(name = "testImpl2")        // 只有一个实现类时,可以不设置 name 或 type
    // @Resource(type = TestImpl1.class)
    ITest obj;
    @Resource
    TestImpl1 testImpl; // type 可识别
    @Resource
    ITest testImpl2;    // name 可识别

    @Autowired
    @Qualifier("testImpl2")
    ITest obj;
    @Autowired
    TestImpl1 testImpl; // type 可识别
    @Autowired
    ITest testImpl2;    // name 可识别
相关推荐
石山代码3 小时前
ArrayList / HashMap / ConcurrentHashMap
java·开发语言
AskHarries4 小时前
系统提示词、开发者指令和用户输入的优先级
java·前端·数据库
daidaidaiyu4 小时前
ThingsBoard 规则链系统源码分析和自定义定时器
java
小毛驴8505 小时前
spring-boot-maven-plugin,maven-compiler-plugin 功能对比
java·python·maven
csdn_aspnet5 小时前
Java 霍尔分区算法(Hoare‘s Partition Algorithm)
java·开发语言·算法
霸道流氓气质5 小时前
通义灵码 IDEA 插件完全使用指南
java·ide·intellij-idea
诸葛务农5 小时前
道路行驶条件下电动汽车永磁电机的有效使用寿命及永磁体的失效和回收再利用(下)
java·开发语言·算法
Percep_gan6 小时前
Java8中的stream的测试使用
java
砍材农夫6 小时前
物联网实战:Spring Boot MQTT | MQTT 设备模拟器演示(附源码)
java·spring boot·后端·物联网·spring·netty
EAIReport6 小时前
Spring AI 详解:Java 开发者快速落地 AI 应用
java·人工智能·spring