使用Spring編寫企業Web應用程序時,服務層中的服務量可能會增加。
服務層中的每個服務可能會消耗其他服務,這些服務將通過@Autowire注入。
問題:當服務數量開始增加時,可能會發生循環依賴性。 它不必指出設計問題……只要在許多服務中自動連接并消耗其他服務之一的中央服務就足夠了,就可能發生循環依賴。
循環依賴關系將導致Spring Application Context失敗,并且癥狀是一個錯誤,清楚地表明了問題所在:
名稱為'*********'的Bean已被注入其他Bean [******,**********,**********, **********]的原始版本(作為循環引用的一部分),
但最終被包裝(例如,作為自動代理創建的一部分)。 這意味著所說的其他bean不使用該bean的最終版本。 這通常是過度渴望類型匹配的結果–例如,考慮在關閉“ allowEagerInit”標志的情況下使用“ getBeanNamesOfType”。
現代Spring應用程序中的問題是,bean是通過@nnotations(而不是通過XML)定義的,而allowEagerInit標志的選項根本不存在。
用@Lazy注釋類的替代解決方案對我來說根本不起作用。
可行的解決方案是將default-lazy-init =“ true”添加到應用程序配置xml文件中:
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true" xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd ><context:component-scan base-package="com.package"></context:component-scan>
<context:annotation-config/>
...
</beans>
希望這可以幫助。 不知道為什么它不是默認配置。
如果您對為什么這種配置可能不滿意有任何建議,請與我們所有人分享。
更新:
經過重新設計后,上述解決方案根本無法解決問題。
因此,我設計了更積極的解決方案以5個步驟解決該問題 。
祝好運!
參考:通過Gal Levinsky博客博客中的JCG合作伙伴 Gal Levinsky 解決了Spring Autowiring中的循環依賴問題 。
翻譯自: https://www.javacodegeeks.com/2012/08/resolve-circular-dependency-in-spring.html