Spring 循环引用解决方案

本文深入探讨了Spring框架中出现的循环引用问题,分析了其根本原因在于代码设计的过度耦合。通过调整代码结构和配置,提供了解决方案,包括代码解耦和修改Spring配置以允许原始依赖注入。此外,还分享了在不同项目融合时可能出现的问题及应对策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值