spring bean 循环依赖 Requested bean is currently in creation: Is there an unresolvable circular referen...

Requested bean is currently in creation: Is there an unresolvable circular reference?

spring bean 循环依赖 - 毛毛 - 毛毛的博客
 getBean的时候由于bean之间存在循环依赖出现类似的错误,先做一个简单实验模拟一下这个异常出现的原因:
bean.xml配置如下:
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
       default-autowire="byName">
<bean id="a" class="BeanA" scope="prototype"/>
<bean id="b" class="BeanB" scope="prototype"/>
</beans>
 
BeanA类如下:
public class BeanA 
{
private BeanB b;
public BeanB getB() {
return b;
}
public void setB(BeanB b) {
this.b = b;
}
}
 
BeanB类如下:
public class BeanB 
{
private BeanA a;
public BeanA getA() {
return a;
}
public void setA(BeanA a) {
this.a = a;
}
}
程序执行的堆栈信息:
spring bean 循环依赖 - 毛毛 - 毛毛的博客
 
bean在初始化的同时会初始化相应的属性(byName),a在初始化的时候会创建a.b,a.b在初始化的时候会创建a.b.a,形成了一个环,所以在AbstractBeanFactory.doGetBean(这里会出现递归调用) 时候 ,走到:
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
会抛出一个异常:Requested bean is currently in creation: Is there an unresolvable circular reference,然后scope是singlton或者其他的时候bean的创建过程不一样,不会有一个这样子的判断,因而不会抛出这样子的错误。
因为scope=prototype,所以每次请求对应不同的bean,所以在创建的时候有一个依赖的先后顺序,而如果bean配置成singleton,则属性间初始化的顺序可以无所谓了,所有的bean都只有一份,所以在bean是singleton时候不会报unresolvable circular reference的错误。

转载于:https://www.cnblogs.com/mean/articles/7549935.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值