Spring 解決循環依賴的 3 種方式

程序員小皮 發佈 2020-02-10T16:21:33+00:00

循環依賴就是N個類中循環嵌套引用,如果在日常開發中我們用new對象的方式發生這種循環依賴的話程序會在運行時一直循環調用,直至內存溢出報錯。

循環依賴就是N個類中循環嵌套引用,如果在日常開發中我們用new 對象的方式發生這種循環依賴的話程序會在運行時一直循環調用,直至內存溢出報錯。

下面說一下Spring是如果解決循環依賴的。

第一種:構造器參數循環依賴

Spring容器會將每一個正在創建的Bean 標識符放在一個「當前創建Bean池」中,Bean標識符在創建過程中將一直保持在這個池中。

因此如果在創建Bean過程中發現自己已經在「當前創建Bean池」里時將拋出BeanCurrentlyInCreationException異常表示循環依賴;而對於創建完畢的Bean將從「當前創建Bean池」中清除掉。

首先我們先初始化三個Bean。


OK,上面是很基本的3個類,StudentA有參構造是StudentB。StudentB的有參構造是StudentC,StudentC的有參構造是StudentA ,這樣就產生了一個循環依賴的情況。

我們都把這三個Bean交給 Spring 管理,並用有參構造實例化。


下面是測試類:

執行結果報錯信息為:

如果大家理解開頭那句話的話,這個報錯應該不驚訝,Spring容器先創建單例StudentA,StudentA依賴StudentB,然後將A放在「當前創建Bean池」中。

此時創建StudentB,StudentB依賴StudentC ,然後將B放在「當前創建Bean池」中,此時創建StudentC,StudentC又依賴StudentA。

但是,此時Student已經在池中,所以會報錯,因為在池中的Bean都是未初始化完的,所以會依賴錯誤 ,初始化完的Bean會從池中移除。

第二種:setter方式單例,默認方式

如果要說setter方式注入的話,我們最好先看一張Spring中Bean實例化的圖

如圖中前兩步驟得知:Spring是先將Bean對象實例化之後再設置對象屬性的,Spring 中的 bean 為什麼默認單例, 這篇建議大家看下。

關注微信公眾號:Java技術棧,在後台回覆:spring,可以獲取我整理的 N 篇最新 Spring 教程,都是乾貨。

修改配置文件為set方式注入

<!--scope="singleton"(默認就是單例方式) -->
<bean id="a" class="com.zfx.student.StudentA" scope="singleton">
<property name="studentB" ref="b"></property>
</bean>
<bean id="b" class="com.zfx.student.StudentB" scope="singleton">

<property name="studentC" ref="c"></property>
</bean>
<bean id="c" class="com.zfx.student.StudentC" scope="singleton">
<property name="studentA" ref="a"></property>
</bean>

下面是測試類:

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("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

修改配置文件為:

scope="prototype" 意思是 每次請求都會創建一個實例對象。

兩者的區別是:有狀態的bean都使用Prototype作用域,無狀態的一般都使用singleton單例作用域。

測試用例:

列印結果:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?

為什麼原型模式就報錯了呢

對於「prototype」作用域Bean,Spring容器無法完成依賴注入,因為「prototype」作用域的Bean,Spring容器不進行緩存,因此無法提前暴露一個創建中的Bean。

關鍵字: