有時候,在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"/>