spring bean 循環依賴 Requested bean is currently in creation: Is there an unresolvable circular reference?


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的錯誤。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM