前言
这段时间在做毕业设计的一个springboot项目,开发功能的过程中,由于两个Service互相注入了对方的实例,导致项目启动时就报了循环依赖异常。循环依赖这个东西,平时只出现在了面试题里,这次被自己碰上了,就仔细去研究了一下解决方式,顺带着复习了循环依赖问题。这里就做一个分享,希望可以帮到大家,谢谢!
场景重现
这里就简单写两个Service,让它们互相注入实例,只是为了复现循环依赖的问题,业务逻辑就不写了。会出现两个Service互相调用的情况
AService
public interface AService {
}
@Service
public class AServiceImpl implements AService {
@Autowired
private BService bService;
}
BService
public interface BService {
}
@Service
public class BServiceImpl implements BService {
@Autowired
private AService aService;
}
项目中存在上述两个Service,在项目启动时,会抛出异常:
解决方案
1、优化代码结构
重新设计代码结构或调用流程,尽量避免两个Service互相调用的过程。
2、allow-circular-references
在配置文件中,进行如下配置,再次启动项目,可以发现 不会出现循环依赖的报错了,项目可以正常启动。
spring:
main:
allow-circular-references: true
这里是给allow-circular-references
这个配置项设置了true,字面意思看就是允许循环依赖
,配置了true之后,Spring会使用三级缓存
去处理循环依赖问题。
3、@Lazy
在其中一个Service使用@Autowired注解注入另一个Service时,添加@Lazy
注解,延迟它的加载。
@Service
public class AServiceImpl implements AService {
@Autowired
@Lazy
private BService bService;
}
@Service
public class BServiceImpl implements BService {
@Autowired
private AService aService;
}