Spring循環依賴的三種方式

 

          引言:循環依賴就是N個類中循環嵌套引用,若是在平常開發中咱們用new 對象的方式發生這種循環依賴的話程序會在運行時一直循環調用,直至內存溢出報錯。下面說一下Spring是若是解決循環依賴的。html

 

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

 

 

Spring容器會將每個正在建立的Bean 標識符放在一個「當前建立Bean池」中,Bean標識符在建立過程當中將一直保持
在這個池中,所以若是在建立Bean過程當中發現本身已經在「當前建立Bean池」裏時將拋出
BeanCurrentlyInCreationException異常表示循環依賴;而對於建立完畢的Bean將從「當前建立Bean池」中清除掉。java

 

首先咱們先初始化三個Bean。spring

[java] view plain copy緩存

  1. public class StudentA {  
  2.   
  3.     private StudentB studentB ;  
  4.   
  5.     public void setStudentB(StudentB studentB) {  
  6.         this.studentB = studentB;  
  7.     }  
  8.   
  9.     public StudentA() {  
  10.     }  
  11.       
  12.     public StudentA(StudentB studentB) {  
  13.         this.studentB = studentB;  
  14.     }  
  15. }  


[java] view plain copyapp

  1. public class StudentB {  
  2.   
  3.     private StudentC studentC ;  
  4.   
  5.     public void setStudentC(StudentC studentC) {  
  6.         this.studentC = studentC;  
  7.     }  
  8.       
  9.     public StudentB() {  
  10.     }  
  11.   
  12.     public StudentB(StudentC studentC) {  
  13.         this.studentC = studentC;  
  14.     }  
  15. }  

[java] view plain copy測試

  1. public class StudentC {  
  2.   
  3.     private StudentA studentA ;  
  4.   
  5.     public void setStudentA(StudentA studentA) {  
  6.         this.studentA = studentA;  
  7.     }  
  8.   
  9.     public StudentC() {  
  10.     }  
  11.    
  12.     public StudentC(StudentA studentA) {  
  13.         this.studentA = studentA;  
  14.     }  
  15. }  


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

 

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

 

[html] view plain copyspa

  1. <bean id="a" class="com.zfx.student.StudentA">  
  2.     <constructor-arg index="0" ref="b"></constructor-arg>  
  3. </bean>  
  4. <bean id="b" class="com.zfx.student.StudentB">  
  5.     <constructor-arg index="0" ref="c"></constructor-arg>  
  6. </bean>  
  7. <bean id="c" class="com.zfx.student.StudentC">  
  8.     <constructor-arg index="0" ref="a"></constructor-arg>  
  9. </bean>   

 

下面是測試類:.net

 

[java] view plain copy

  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");  
  4.         //System.out.println(context.getBean("a", StudentA.class));  
  5.     }  
  6. }  


執行結果報錯信息爲:

 

 

[java] view plain copy

  1. Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:   
  2.     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是先將Bean對象實例化以後再設置對象屬性的

 

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

 

[html] view plain copy

  1. <!--scope="singleton"(默認就是單例方式)  -->  
  2. <bean id="a" class="com.zfx.student.StudentA" scope="singleton">  
  3.     <property name="studentB" ref="b"></property>  
  4. </bean>  
  5. <bean id="b" class="com.zfx.student.StudentB" scope="singleton">  
  6.     <property name="studentC" ref="c"></property>  
  7. </bean>  
  8. <bean id="c" class="com.zfx.student.StudentC" scope="singleton">  
  9.     <property name="studentA" ref="a"></property>  
  10. </bean>  


下面是測試類:

 

 

[java] view plain copy

  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");  
  4.         System.out.println(context.getBean("a", StudentA.class));  
  5.     }  
  6. }  


打印結果爲:

 

 

[java] view plain copy

  1. com.zfx.student.StudentA@1fbfd6  


爲何用set方式就不報錯了呢 ?

 

    咱們結合上面那張圖看,Spring先是用構造實例化Bean對象 ,此時Spring會將這個實例化結束的對象放到一個Map中,而且Spring提供了獲取這個未設置屬性的實例化對象引用的方法。   結合咱們的實例來看,,當Spring實例化了StudentA、StudentB、StudentC後,緊接着會去設置對象的屬性,此時StudentA依賴StudentB,就會去Map中取出存在裏面的單例StudentB對象,以此類推,不會出來循環的問題嘍、

 

下面是Spring源碼中的實現方法,。如下的源碼在Spring的Bean包中的DefaultSingletonBeanRegistry.java類中

 

[java] view plain copy

  1. /** Cache of singleton objects: bean name --> bean instance(緩存單例實例化對象的Map集合) */  
  2.     private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);  
  3.       
  4.     /** Cache of singleton factories: bean name --> ObjectFactory(單例的工廠Bean緩存集合) */  
  5.     private final Map<String, ObjectFactory> singletonFactories = new HashMap<String, ObjectFactory>(16);  
  6.       
  7.     /** Cache of early singleton objects: bean name --> bean instance(早期的單身對象緩存集合) */  
  8.     private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);  
  9.       
  10.     /** Set of registered singletons, containing the bean names in registration order(單例的實例化對象名稱集合) */  
  11.     private final Set<String> registeredSingletons = new LinkedHashSet<String>(64);  
  12.     /** 
  13.      * 添加單例實例 
  14.      * 解決循環引用的問題 
  15.      * Add the given singleton factory for building the specified singleton 
  16.      * if necessary. 
  17.      * <p>To be called for eager registration of singletons, e.g. to be able to 
  18.      * resolve circular references. 
  19.      * @param beanName the name of the bean 
  20.      * @param singletonFactory the factory for the singleton object 
  21.      */  
  22.     protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) {  
  23.         Assert.notNull(singletonFactory, "Singleton factory must not be null");  
  24.         synchronized (this.singletonObjects) {  
  25.             if (!this.singletonObjects.containsKey(beanName)) {  
  26.                 this.singletonFactories.put(beanName, singletonFactory);  
  27.                 this.earlySingletonObjects.remove(beanName);  
  28.                 this.registeredSingletons.add(beanName);  
  29.             }  
  30.         }  
  31.     }  


 

 

 

第三種:setter方式原型,prototype

 

 

修改配置文件爲:

 

[html] view plain copy

  1. <bean id="a" class="com.zfx.student.StudentA" <span style="color:#FF0000;">scope="prototype"</span>>  
  2.         <property name="studentB" ref="b"></property>  
  3.     </bean>  
  4.     <bean id="b" class="com.zfx.student.StudentB" <span style="color:#FF0000;">scope="prototype"</span>>  
  5.         <property name="studentC" ref="c"></property>  
  6.     </bean>  
  7.     <bean id="c" class="com.zfx.student.StudentC" <span style="color:#FF0000;">scope="prototype"</span>>  
  8.         <property name="studentA" ref="a"></property>  
  9.     </bean>  


scope="prototype" 意思是 每次請求都會建立一個實例對象。二者的區別是:有狀態的bean都使用Prototype做用域,無狀態的通常都使用singleton單例做用域。

測試用例:

 

[java] view plain copy

  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");  
  4.         <strong>//此時必需要獲取Spring管理的實例,由於如今scope="prototype" 只有請求獲取的時候纔會實例化對象</strong>  
  5.         System.out.println(context.getBean("a", StudentA.class));  
  6.     }  
  7. }  

打印結果:

 

[java] view plain copy

  1. Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:   
  2.     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。

相關文章
相關標籤/搜索