1. 程式人生 > >Spring 迴圈引用解決方案

Spring 迴圈引用解決方案

Spring 迴圈引用解決方案

一、問題呈現:

 

上述memberMerchantService 和 memberService 互相引用或者深層注入引用 導致專案啟動不了

【詳細問題描述】:

Bean with name ‘xxxService’ has been injected into other beans [xxxService] in its raw version as part of a circular reference, but has eventually been wrapped. 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. 

 【簡單分析 導致原因】:

程式碼設計得比較耦合,將相關邏輯拆分後得到解決。不管我如何拆解都如影隨形,已經不是簡單的A->B,B->A的迴圈引用了,而是深層次的邏輯耦合,要解耦比較困難,說明在設計階段有提高的餘地。詭異的是,在融入另一個專案前是不會拋這個錯誤的,可見問題可能出在和新專案融合後的配置檔案上。

大神Juergen Hoeller說:

This is probably a consequence of the bean initialization order having changed, in combination with auto-proxying and maybe a pointcut that is too broad.

二、解決方案: 

 (一)、解耦合,從本質出發,分析程式碼我們知道,memberMerchantService 與memberService互相深層注入引用,導致迴圈引用,去掉一方或者替代掉即可

(二)、解決方案,有一個引數setAllowRawInjectionDespiteWrapping,預設是false,將其設成true即可。程式碼如下:【參考文獻】

public class MyWebApplicationContext extends XmlWebApplicationContext {
    @Override
    protected DefaultListableBeanFactory createBeanFactory() {
        DefaultListableBeanFactory beanFactory = super.createBeanFactory();
        beanFactory.setAllowRawInjectionDespiteWrapping(true);
        return beanFactory;
    }
}

然後在web.xml配置啟用此context

<context-param>        
    <param-name>contextClass</param-name>        
    <param-value>xxx.MyWebApplicationContext</param-value>    
</context-param>