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

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

相关推荐
Victor3562 小时前
Redis(16)Redis的有序集合(Sorted Set)类型有哪些常用命令?
后端
Victor3562 小时前
Redis(17)如何在Redis中设置键的过期时间?
后端
22jimmy2 小时前
JavaWeb(二)CSS
java·开发语言·前端·css·入门·基础
vvilkim5 小时前
Java主流框架全解析:从企业级开发到云原生
java·运维·云原生
MZ_ZXD0016 小时前
springboot汽车租赁服务管理系统-计算机毕业设计源码58196
java·c++·spring boot·python·django·flask·php
A 计算机毕业设计-小途6 小时前
大四零基础用Vue+ElementUI一周做完化妆品推荐系统?
java·大数据·hadoop·python·spark·毕业设计·毕设
岁忧8 小时前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
你的人类朋友10 小时前
说说git的变基
前端·git·后端
阿杆10 小时前
玩转 Amazon ElastiCache 免费套餐:小白也能上手
后端
阿杆10 小时前
无服务器每日自动推送 B 站热门视频
后端