当前位置: 首页 > news >正文

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

介绍

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

案例

父类Base

public class Base {public int i;public Base(){};public Base(int i){this.i = i;}
}

子类TestBase继承Base

public class TestBase extends Base{
}

test中依赖了Base类型的对象

public class Test {@Autowiredpublic Base base;@PostConstructpublic void init(){System.out.println(base.i);}
}

TestConfig配置类

public class TestConfig {@Beanpublic Base base1(){System.out.println("base1");return new Base(1);}@Beanpublic TestBase testBase(){System.out.println("testBase");return new TestBase();}@Beanpublic 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两种类型。

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

http://www.lryc.cn/news/150924.html

相关文章:

  • 海外腾讯云服务器手机上无法访问外网怎么办??
  • python3+requests:接口自动化测试(二)
  • uni-app:允许字符间能自动换行(英文字符、数字等)
  • day 42 |● 121. 买卖股票的最佳时机 ● 122.买卖股票的最佳时机II
  • SQLserver基础入门理论(超基础)
  • (三)行为模式:7、观察者模式(Observer Pattern)(C++示例)
  • 2019CVPR Semantic Graph Convolutional Networks for 3D Human Pose Regression
  • 大数据课程K16——Spark的梯度下降法
  • springboot:时间格式化的5种方法(解决后端传给前端的时间格式转换问题)推荐使用第4和第5种!
  • 六、vim编辑器的使用
  • 【易售小程序项目】项目介绍与系列文章集合
  • 游戏服务器成DDoS最大攻击重灾区
  • [SpringBoot3]博客管理系统(源码放评论区了)
  • C语言——指针基本语法
  • elementui table 在浏览器分辨率变化的时候界面异常
  • 六、Kafka-Eagle监控
  • DBeaver 23.1.5 发布
  • 三种垃圾收集算法,优缺点分析,设计垃圾收集
  • 【链表OJ 10】环形链表Ⅱ(求入环节点)
  • RT-Thread在STM32硬件I2C的踩坑记录
  • 小白学Go基础01-Go 语言的介绍
  • Spring工具类--Assert的使用
  • 无涯教程-Android - Absolute Layout函数
  • 2018ECCV Can 3D Pose be Learned from2D Projections Alone?
  • 干旱演变研究:定义及研究方法
  • 【LeetCode-中等题】114. 二叉树展开为链表
  • 【题解】JZOJ6645 / 洛谷P4090 [USACO17DEC] Greedy Gift Takers P
  • Vue 项目中的错误如何处理的?
  • 网络分层的真实含义
  • RT-Thread 线程间同步