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;
}
复制代码

 

 


 

posted @   《END》  阅读(130)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示