springboot循环依赖
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xxxConfiguration': Unsatisfied dependency expressed through field 'xxxService'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'xxxServiceImpl': Bean with name 'xxxServiceImpl' has been injected into other beans [xxxServiceImpl] 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 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.
循环依赖是指两个或多个Bean互相依赖的情况,在Spring容器初始化时会出现循环依赖的问题。对于循环依赖,Spring在初始化过程中采用了“提前暴露”的策略,将尚未完全初始化的Bean对象暴露给其他需要依赖的Bean对象,以便后者能够完成初始化。
常见的循环依赖场景:
@Service public class AImpl implements IAService { @Autowired private IBService bService; } @Service public class BImpl implements IBService { @Autowired private IAService aService; }
解决循环依赖的方法:
一、A类service引用B类service,B类引用A类mapper @Service public class AImpl implements IAService { @Autowired private IBService bService; } @Service public class BImpl implements IBService { @Autowired private AMapper aMapper; } 二、A类service引用B类service,B类使用spring工具类获取A类service实现类的bean @Service public class AImpl implements IAService { @Autowired private IBService bService; } @Service public class BImpl implements IBService { public void test() { AServiceImpl bean = SpringUtil.getBean(AServiceImpl.class); } } 三、使用@Lazy懒加载注解 @Service public class AImpl implements IAService { @Autowired private IBService bService; } @Service public class BImpl implements IBService { @Lazy @Autowired private IAService aService; }
分类:
JAVA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~