@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 可识别
相关推荐
lUie INGA2 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
geBR OTTE2 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu2 小时前
博客系统UI自动化测试报告
java
Aurorar0rua3 小时前
CS50 x 2024 Notes C - 05
java·c语言·数据结构
Cosmoshhhyyy4 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
布谷歌4 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
eLIN TECE4 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
老神在在0014 小时前
Spring Bean 的六种作用域详解
java·后端·spring
仙草不加料4 小时前
互联网大厂Java面试故事实录:三轮场景化技术提问与详细答案解析
java·spring boot·微服务·面试·aigc·电商·内容社区
程序员老邢5 小时前
【技术底稿 19】Redis7 集群密码配置 + 权限锁死 + 磁盘占满连锁故障真实排查全记录
java·服务器·经验分享·redis·程序人生·微服务