SpringBoot 循环依赖,如何解决?
什么是循环依赖?
循环依赖是指在Spring Boot 应用程序中,两个或多个类之间存在彼此依赖的情况,形成一个循环依赖链。
在这种情况下,当一个类在初始化时需要另一个类的实例,而另一个类又需要第一个类的实例时,就会出现循环依赖问题。这会导致应用程序无法正确地初始化和运行,因为Spring Boot 无法处理这种循环依赖关系。
问题及症状
在2.6.0之前,Spring Boot会自动处理循环依赖的问题。2.6.0及之后的版本会默认检查循环依赖,存在该问题则会报错。
ComponentA类注入ComponentB类,ComponentB类注入ComponentA类,就会发生循环依赖的问题。
ComponentA
import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class ComponentA { @Resource private ComponentB componentB; }
ComponentB
import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class ComponentB { @Resource private ComponentA componentA; }
错误
现在,2.6.0 这个版本已经默认禁止 Bean 之间的循环引用, 则基于上面的代码
下一篇:
分库分表后的查询解决方案