Spring 循环引用解决方案

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caox_nazi/article/details/82967030

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>

猜你喜欢

转载自blog.csdn.net/caox_nazi/article/details/82967030
今日推荐