天天看點

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

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

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

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

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

Spring容器會将每一個正在建立的Bean 辨別符放在一個“目前建立Bean池”中,Bean辨別符在建立過程中将一直保持在這個池中。

是以如果在建立Bean過程中發現自己已經在“目前建立Bean池”裡時将抛出BeanCurrentlyInCreationException異常表示循環依賴;而對于建立完畢的Bean将從“目前建立Bean池”中清除掉。

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

Spring 解決循環依賴的 3 種方式!
Spring 解決循環依賴的 3 種方式!
Spring 解決循環依賴的 3 種方式!
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?      

如果大家了解開頭那句話的話,這個報錯應該不驚訝,Spring容器先建立單例StudentA,StudentA依賴StudentB,然後将A放在“目前建立Bean池”中。

此時建立StudentB,StudentB依賴StudentC ,然後将B放在“目前建立Bean池”中,此時建立StudentC,StudentC又依賴StudentA。

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

第二種:setter方式單例,預設方式

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

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

如圖中前兩步驟得知:Spring是先将Bean對象執行個體化之後再設定對象屬性的,Spring 中的 bean 為什麼預設單例, 這篇建議大家看下。

關注微信公衆号:Java技術棧,在背景回複:spring,可以擷取我整理的 N 篇最新 Spring 教程,都是幹貨。

修改配置檔案為set方式注入

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

為什麼用set方式就不報錯了呢 ?

我們結合上面那張圖看,Spring先是用構造執行個體化Bean對象 ,此時 Spring 會将這個執行個體化結束的對象放到一個Map中,并且 Spring 提供了擷取這個未設定屬性的執行個體化對象引用的方法。

結合我們的執行個體來看,當Spring執行個體化了StudentA、StudentB、StudentC後,緊接着會去設定對象的屬性,此時StudentA依賴StudentB,就會去Map中取出存在裡面的單例StudentB對象,以此類推,不會出來循環的問題喽、

下面是Spring源碼中的實作方法。以下的源碼在Spring的Bean包中的DefaultSingletonBeanRegistry.java類中

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

第三種:setter方式原型,prototype

修改配置檔案為:

<bean id="a" class="com.zfx.student.StudentA" scope="prototype">
  <property name="studentB" ref="b"></property>
</bean>
<bean id="b" class="com.zfx.student.StudentB" scope="prototype">
  <property name="studentC" ref="c"></property>
</bean>
<bean id="c" class="com.zfx.student.StudentC" scope="prototype">
  <property name="studentA" ref="a"></property>
</bean>      

scope="prototype" 意思是 每次請求都會建立一個執行個體對象。

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

測試用例:

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("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 bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?      

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

對于“prototype”作用域Bean,Spring容器無法完成依賴注入,因為“prototype”作用域的Bean,Spring容器不進行緩存,是以無法提前暴露一個建立中的Bean。

推薦去我的部落格閱讀更多:

1.Java JVM、集合、多線程、新特性系列教程

2.Spring MVC、Spring Boot、Spring Cloud 系列教程

3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程

4.Java、後端、架構、阿裡巴巴等大廠最新面試題

覺得不錯,别忘了點贊+轉發哦!

繼續閱讀