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后,在容器中有着TestBaseBase两种类型。

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

相关推荐
想用offer打牌7 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
曹牧8 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX8 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了9 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法9 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7259 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎9 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄9 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
Moment9 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
忆~遂愿10 小时前
ops-cv 算子库深度解析:面向视觉任务的硬件优化与数据布局(NCHW/NHWC)策略
java·大数据·linux·人工智能