spring的循环依赖

先来几个常见的面试题:

1、你解释下spring的三级缓存?

2、三级缓存分别是什么?三个Map有什么异同?

3、什么是循环依赖?请你谈谈

4、如何检测是否存在循环依赖?实际开发中见过循环依赖的异常吗

5、多例情况下,循环依赖问题为什么无法解决

什么是循环依赖:

多个bean之间相互依赖,形成了一个闭环。比如:A 依赖于B,B依赖于C,C依赖于A

通常来说,如果问Spring的内部如何解决循环依赖,一定是指默认的单例bean中,属性相互引用的场景。

 两种注入方式对循环依赖的影响

循环依赖 的官方说明:

Circular dependencies

If you use predominantly constructor injection, it is possible to create an unresolvable circular dependency scenario.

For example: Class A requires 姐an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection. If you configure beans for classes A and B to be injected into each other, the Spring IoC container detects this circular reference at runtime, and throws a BeanCurrentlyInCreationException.

One possible solution is to edit the source code of some classes to be configured by setters rather than constructors. Alternatively, avoid constructor injection and use setter injection only. In other words, although it is not recommended, you can configure circular dependencies with setter injection.

Unlike the typical case (with no circular dependencies), a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken-and-egg scenario).

结论:我们AB循环依赖报错问题只要A的注入方式是setter且singleton,就不会有循环依赖的问题。

spring循环依赖纯java代码验证案例

Spring容器循环报错演示 BeanCurrentlylnCreationException

循环依赖现象在spring容器中注入依赖的对象,有两种情况

1、 构造器方式注入依赖(不可行)

2、以set方式注入依赖(可行)

代理可参考其他

重要结论(spring内部通过三级缓存来解决循环依赖)DefaultSingletonBeanRegistry

只有单例的bean会通过三级缓存提前暴露来解决循环依赖的问题,而非单例bean,每次从容器中获取都是一个新的对象,都会重新创建,所以非单例的bean是没有缓存的,不会将其放在三级缓存中。

第一级缓存(也叫单例池)singletonObjects:存放已经经历了完整的生命周期的Bean对象。

第二级缓存:earlySingletonObjects:存放早期的暴露出的Bean对象,Bean的生命周期末结束(属性还没填充完)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值