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;
}