@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 可识别
相关推荐
EXI-小洲14 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
2601_9619017015 小时前
SpringBoot使用Nacos进行application.yml配置管理
java·spring boot·spring
何以解忧,唯有..16 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
QQ_216962909616 小时前
【源码编号:project79475】SpringBoot校内二手交易平台:商品发布、分类检索、留言交流、订单管理全流程实战
java·spring boot·后端
前端 贾公子17 小时前
第09章:上下文与记忆 (2)
java·服务器·前端
2601_9622035117 小时前
Java进阶07集合(续)
java·开发语言
郑州光合科技余经理18 小时前
本地生活服务系统:模块边界与结算字段怎么拆
java·开发语言·前端·后端·系统架构·uni-app·php
专注仿真18 小时前
Spring AI 实现智能对话系统项目指南
数据结构·spring·机器学习
roman_日积跬步-终至千里18 小时前
【数据治理(6)】DataOps 不是调度工具,而是让数据产品长期可信的运行机制
java·服务器·网络
落魄大学生之流水线上谋生计18 小时前
LangGraph 基本用法指南
java·windows·python·langchain