Spring迴圈依賴的三種方式

引言:迴圈依賴就是N個類中迴圈巢狀引用,如果在日常開發中我們用new 物件的方式發生這種迴圈依賴的話程式會在執行時一直迴圈呼叫,直至記憶體溢位報錯。下面說一下Spring是如果解決迴圈依賴的。
第一種:構造器引數迴圈依賴
Spring容器會將每一個正在建立的Bean 識別符號放在一個“當前建立Bean池”中,Bean識別符號在建立過程中將一直保持在這個池中。
因此如果在建立Bean過程中發現自己已經在“當前建立Bean池”裡時將丟擲BeanCurrentlyInCreationException異常表示迴圈依賴;而對於建立完畢的Bean將從“當前建立Bean池”中清除掉。
首先我們先初始化三個Bean。



OK,上面是很基本的3個類,,StudentA有參構造是StudentB。StudentB的有參構造是StudentC,StudentC的有參構造是StudentA ,這樣就產生了一個迴圈依賴的情況,
我們都把這三個Bean交給Spring管理,並用有參構造例項化。

下面是測試類:
publicclassTest{
publicstaticvoidmain(String[] args){
ApplicationContext context =newClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
//System.out.println(context.getBean("a", StudentA.class));
}
}
執行結果報錯資訊為:
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating beanwithname'a': Requested beaniscurrentlyincreation:Isthere an unresolvable circular reference?
如果大家理解開頭那句話的話,這個報錯應該不驚訝,Spring容器先建立單例StudentA,StudentA依賴StudentB,然後將A放在“當前建立Bean池”中,此時建立StudentB,StudentB依賴StudentC ,然後將B放在“當前建立Bean池”中,此時建立StudentC,StudentC又依賴StudentA, 但是,此時Student已經在池中,所以會報錯,,因為在池中的Bean都是未初始化完的,所以會依賴錯誤 ,(初始化完的Bean會從池中移除)
第二種:setter方式單例,預設方式
如果要說setter方式注入的話,我們最好先看一張Spring中Bean例項化的圖

如圖中前兩步驟得知:Spring是先將Bean物件例項化之後再設定物件屬性的
修改配置檔案為set方式注入

下面是測試類:
publicclassTest{
publicstaticvoidmain(String[] args){
ApplicationContext context =newClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
System.out.println(context.getBean("a", StudentA.class));
}
}
列印結果為:
com.zfx.student.StudentA@1fbfd6
為什麼用set方式就不報錯了呢 ?
我們結合上面那張圖看, Spring先是用構造例項化 Bean物件 ,此時Spring會將這個例項化結束的物件放到一個Map中,並且Spring提供了獲取這個未設定屬性的例項化物件引用的方法。
結合我們的例項來看,,當Spring例項化了StudentA、StudentB、StudentC後,緊接著會去設定物件的屬性,此時StudentA依賴StudentB,就會去Map中取出存在裡面的單例StudentB物件,以此類推,不會出來迴圈的問題嘍、
下面是Spring原始碼中的實現方法。以下的原始碼在Spring的Bean包中的DefaultSingletonBeanRegistry.java類中

第三種:setter方式原型,prototype
修改配置檔案為:

測試用例:
publicclassTest{
publicstaticvoidmain(String[] args){
ApplicationContext context =newClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
//此時必須要獲取Spring管理的例項,因為現在scope="prototype" 只有請求獲取的時候才會例項化物件
System.out.println(context.getBean("a", StudentA.class));
}
}
列印結果:
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating beanwithname'a': Requested beaniscurrentlyincreation:Isthere an unresolvable circular reference?
為什麼原型模式就報錯了呢 ?
對於“prototype”作用域Bean,Spring容器無法完成依賴注入,因為“prototype”作用域的Bean,Spring容器不進行快取,因此無法提前暴露一個建立中的Bean。
擴充套件閱讀
作者:學習園
來源:https://blog.csdn.net/u010644448/article/details/59108799