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两种类型。

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

相关推荐
多彩电脑1 分钟前
向AIDE(安卓设备上的Android Studio)导入aar库
android·java·开发语言·androidx
Qres8212 分钟前
nodejs安装记录
后端·nodejs
阿维的博客日记10 分钟前
Windows自由切换jdk版本
java·windows
摇滚侠13 分钟前
MyBatis 入门到项目实战 MyBatis 逆向工程 62
java·开发语言·mybatis
IT_陈寒15 分钟前
Vue的响应式让我原地裂开,你们也有这情况吗
前端·人工智能·后端
ch.ju17 分钟前
Java Programming Chapter 4——Multi-level inheritance
java·开发语言
techdashen20 分钟前
用 Rust 真正发出 Ping:FFI 类型、newtype 与 MaybeUninit
开发语言·后端·rust
yuezhilangniao21 分钟前
2026删除K8s命名空间 卡 Terminating 的 ns
java·容器·kubernetes
Boop_wu23 分钟前
[Spring Cloud] 快速上手nacos
后端·spring·spring cloud
GZ_TOGOGO30 分钟前
Spring AI Alibaba 格式化输出
java·人工智能·spring