本篇文章解決以下問題:
- [1] . Spring循環依賴指的是什么?
- [2] . Spring能解決哪種情況的循環依賴?不能解決哪種情況?
- [3] . Spring能解決的循環依賴原理(三級緩存)
一、Spring 循環依賴可能出現的三種方式
第一種:構造器參數循環依賴
第二種:setter方式單例,默認方式 第三種:setter方式原型,prototype
第一種:構造器參數循環依賴
首先我們先初始化三個Bean。
public class StudentA { private StudentB studentB; public void setStudentB(StudentB studentB) { this.studentB = studentB; } public StudentA() { } public StudentA(StudentB studentB) { this.studentB = studentB; } } public class StudentB { private StudentC studentC ; public void setStudentC(StudentC studentC) { this.studentC = studentC; } public StudentB() { } public StudentB(StudentC studentC) { this.studentC = studentC; } } public class StudentC { private StudentA studentA; public void setStudentA(StudentA studentA) { this.studentA = studentA; } public StudentC() { } public StudentC(StudentA studentA) { this.studentA = studentA; } }
application1.xml
<bean id="a" class="cn.mayday.springrecycledp.demo1.StudentA"> <constructor-arg index="0" ref="b"></constructor-arg> </bean> <bean id="b" class="cn.mayday.springrecycledp.demo1.StudentB"> <constructor-arg index="0" ref="c"></constructor-arg> </bean> <bean id="c" class="cn.mayday.springrecycledp.demo1.StudentC"> <constructor-arg index="0" ref="a"></constructor-arg> </bean>
測試類
@Test public void test1() { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext1.xml"); }
測試結果
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容器會將每一個正在創建的Bean
標識符放在一個“當前創建Bean池”中,Bean標識符在創建過程中將一直保持在這個池中。因此如果在創建Bean過程中發現自己已經在“當前創建Bean池”里時將拋出BeanCurrentlyInCreationException異常表示循環依賴;而對於創建完畢的Bean將從“當前創建Bean池”中清除掉。
- 根據上述源碼實現分析:Spring容器先創建單例StudentA,StudentA依賴StudentB,然后將A放在“當前創建Bean池”中,此時創建StudentB, StudentB依賴StudentC ,然后將B放在“當前創建Bean池”中,此時創建StudentC,StudentC又依賴StudentA, 但是,此時StudentA已經在池中,所以會報錯,因為在池中的Bean都是未初始化完的,所以會依賴錯誤 ,(初始化完的Bean會從池中移除)
第二種:setter方式單例,默認方式
application2.xml
<!--scope="singleton"(默認就是單例方式) --> <bean id="a" class="cn.mayday.springrecycledp.demo1.StudentA" scope="singleton"> <property name="studentB" ref="b"></property> </bean> <bean id="b" class="cn.mayday.springrecycledp.demo1.StudentB" scope="singleton"> <property name="studentC" ref="c"></property> </bean> <bean id="c" class="cn.mayday.springrecycledp.demo1.StudentC" scope="singleton"> <property name="studentA" ref="a"></property> </bean>
- 測試類
@Test public void test2() { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext2.xml"); System.out.println(context.getBean("a", StudentA.class)); }
- 測試結果
沒有報錯
- 結果分析
如果要說setter方式注入的話,我們最好先看一張Spring中Bean實例化的圖

如圖中前兩步驟得知:Spring是先將Bean對象實例化之后再設置對象屬性的
- 為什么用set方式就不報錯了呢 ?
結合上面那張圖看,Spring先是用構造實例化Bean對象 ,此時Spring會將這個實例化結束的對象放到一個Map中,並且Spring提供了獲取這個未設置屬性的實例化對象引用的方法。
結合我們的實例來看,,當Spring實例化了StudentA、StudentB、StudentC后,緊接着會去設置對象的屬性,此時StudentA依賴StudentB,就會去Map中取出存在里面的單例StudentB對象,以此類推,不會出來循環的問題嘍。
第三種:setter方式原型,prototype
application3.xml
<!--scope="prototype" --> <bean id="a" class="cn.mayday.springrecycledp.demo1.StudentA" scope="prototype"> <property name="studentB" ref="b"></property> </bean> <bean id="b" class="cn.mayday.springrecycledp.demo1.StudentB" scope="prototype"> <property name="studentC" ref="c"></property> </bean> <bean id="c" class="cn.mayday.springrecycledp.demo1.StudentC" scope="prototype"> <property name="studentA" ref="a"></property> </bean>
測試類
@Test public void test3() { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext3.xml"); 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?
- 為什么原型模式就報錯了呢 ?
scope="prototype" 意思是 每次請求都會創建一個實例對象。
兩者的區別是:有狀態的bean都使用Prototype作用域,無狀態的一般都使用singleton單例作用域。
對於“prototype”作用域Bean,Spring容器無法完成依賴注入,因為“prototype”作用域的Bean,Spring容器不進行緩存,因此無法提前暴露一個創建中的Bean。
-
總結
-
1、 Spring bean初始化的循環依賴只能解決單例模式的set方式(依靠==第三級緩存==提前暴露==無參構造函數==new出的對象)
-
2、 scope="prototype"時,三級緩存不保存非單例模式的bean對象,所以無法解決。
二、 Spring解決單例模式循環依賴原理(三級緩存)
Spring三級緩存請參考文章
Spring源碼初探-IOC(4)-Bean的初始化-循環依賴的解決(講的很明白)
/** Cache of singleton objects: bean name --> bean instance(緩存單例實例化對象的Map集合) */ private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64); /** Cache of singleton factories: bean name --> ObjectFactory(單例的工廠Bean緩存集合) */ private final Map<String, ObjectFactory> singletonFactories = new HashMap<String, ObjectFactory>(16); /** Cache of early singleton objects: bean name --> bean instance(早期的單身對象緩存集合) */ private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16); /** Set of registered singletons, containing the bean names in registration order(單例的實例化對象名稱集合) */ private final Set<String> registeredSingletons = new LinkedHashSet<String>(64); /** * 添加單例實例 * 解決循環引用的問題 * Add the given singleton factory for building the specified singleton * if necessary. * <p>To be called for eager registration of singletons, e.g. to be able to * resolve circular references. * @param beanName the name of the bean * @param singletonFactory the factory for the singleton object */ protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null"); synchronized (this.singletonObjects) { if (!this.singletonObjects.containsKey(beanName)) { this.singletonFactories.put(beanName, singletonFactory); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); } } }
參考文章:
1 面試必問:Spring 循環依賴的三種方式
2 Spring源碼初探-IOC(4)-Bean的初始化-循環依賴的解決(講的很明白)
歡迎關注微信公眾號:shoshana