Spring中依赖注入的继承bean的细节问题

介绍

有时我们会对一种类型的bean进行继承,在Spring生成bean的时候,返回类型有时是子类类型,有时会父类类型。那么到底在什么情况下用哪种类型呢?肯定有不少人会忽略这点,本篇文章就是把这个细节讲清楚

案例

父类Base

java 复制代码
public class Base {
    
    public int i;
    
    public Base(){};
    
    public Base(int i){
        this.i = i;
    }
}

子类TestBase继承Base

java 复制代码
public class TestBase extends Base{
}

test中依赖了Base类型的对象

java 复制代码
public class Test {
    
    @Autowired
    public Base base;
    
    @PostConstruct
    public void init(){
        System.out.println(base.i);
    }
}

TestConfig配置类

java 复制代码
public class TestConfig {
    
    @Bean
    public Base base1(){
        System.out.println("base1");
        return new Base(1);
    }
    
    @Bean
    public TestBase testBase(){
        System.out.println("testBase");
        return new TestBase();
    }
    
    @Bean
    public Test test(){
        return new Test();
    }
}

重点来了,TestConfig中生成了Base类型的对象base1,和TestBase类型的对象testBase,TestBase继承了Base,
Test对象依赖注入了Base 类型的对象base

容器启动结果

复制代码
Description:

Field base in com.example.test.Test required a single bean, but 2 were found:
	- base1: defined by method 'base1' in class path resource [com/example/test/TestConfig.class]
	- testBase: defined by method 'testBase' in class path resource [com/example/test/TestConfig.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

启动错误,提示要注入的base发现了两个bean,这说明虽然注入对象testBase类型是TestBase,但因为继承了Base关系,所以还当对象被依赖Base类型时,testBase对象也算进Base类型中。也就是说testBase的对象生成bean后,在容器中有着TestBase和Base两种类型。

这是极小的细节,这部分源码本人没有看,其实也没必要,记住这个特点就可以了

相关推荐
秋饼13 分钟前
LLM API密钥动态轮换实战:Spring Vault + Spring AI + 多Provider路由
java·ai·技术分享·后端开发
马良神笔1 小时前
2026 年Rag最近技术前沿总结
后端·python·django
程序猿DD1 小时前
同样10美元,OpenDesign和Command Code的DeepSeek V4.1 Flash额度到底有多少?
后端
福兮说2 小时前
JSON 格式正确,数据就可靠吗?我用一份自编配置检查类型与空值
java·前端·json
高频因子挖掘机2 小时前
A股量化从日线升级到5分钟线:数据量增加后最先暴露哪些工程问题?
后端·github·api
高频因子挖掘机2 小时前
历史行情返回顺序变了,为什么按行号计算指标很危险?
后端·github·api
紧跟先前的步伐3 小时前
Go AI Agent 实战 03|Token、上下文窗口与模型调用成本
java·人工智能·golang
const_qiu4 小时前
第四章 00:开篇 —— 从「会聊天」到「记得住、会干活、能协作」
java·开发语言·人工智能·python
Wang's Blog4 小时前
Java 项目实战: 交友项目 - 个人资料管理的更新接口实现与坑
java·开发语言·交友
团子哒哒4 小时前
数组、切片和Map
后端