循環依賴,就是說類A依賴與B,而B又依賴於A,這種情況本不應該發生,發生這種情況是因為我在項目中使用的工廠模式,用一個工廠來生產一些管理器類,而某一管理器要需要另一管理器提供支持所以就要引用工廠類,而這個管理器和這個工廠就出現了循環依賴(項目中實際的邏輯比這個更復雜,因為我在項目中實現的了一個工作流數據POJO類延遲加載的功能像hibernate 那樣在調用一個類的集合屬性時才到要shark中去查找數據而不是在new里加載,並且這個數據類的集合屬性並不包含加載數據的代碼只是普通的Bean方法get,set),查了一下spring的doc,解決方法很簡單加個lazy-init="true"就可以了,及在初始化時不建立類而是在使用時才建立。
<bean id="wfDataProxyFactory"
class="com.dgsoft.wf.data.proxy.WfDataProxyFactory"
lazy-init="true">
<!-- manager need -->
<property name="processMgr">
<ref bean="processMgr" />
</property>
<property name="processInstanceMgr">
<ref bean="processInstanceMgr" />
</property>
<property name="workMgr">
<ref bean="workMgr" />
</property>
</bean>
有時候,在SPRING中兩個類互相含有對方的聲明,一般情況這是不允許並且極可能是有錯誤的。
會報這個錯:
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘***’: Bean with name ‘***’ has been injected into other beans [***, ***]in its raw version as part of a circular reference,
but has eventually been wrapped (for example as part of auto-proxy creation). This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using ‘getBeanNamesOfType’ with the ‘allowEagerInit’ flag turned off, for example.
但有時候這正是我們想要的,考慮這種情況:
我們用一個ManagerFactory來包含所有Manager的聲明,以便在程序中用到多個Manager的地方,一個入口集中訪問。但是,可能某個Manager本身就需要用到其它幾個Manager,進而用到ManagerFactory。這時,我們可以這樣聲明即可:
<bean id="managerFactory" class="common.utils.ManagerFactory" lazy-init="true"/>