SPRING循环依赖(circular reference)的解决方法

循环依赖,就是说类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"/>

 

posted @ 2014-10-21 18:07  IcreamPrince  阅读(15751)  评论(2编辑  收藏  举报