Spring循环依赖问题解决

1,458 阅读1分钟

The dependencies of some of the beans in the application context form a cycle:

最近在升级spring-boot 2.12.RELEASE 到2.7.0的过程中遇到了循环依赖的问题。

循环依赖

当一个beanA依赖另一个beanB,并且beanB也依赖于beanA时就会发生循环依赖。 beanA -> beanB -> beanA

一个简单的例子

定义两个相互依赖的bean

public class BeanA {

    @Autowired
    private BeanB beanb;
    
}
@Component
public class BeanB {

    @Autowired
    private BeanA beanA;
    
}

启动Application得到:


APPLICATION FAILED TO START


Description:

The dependencies of some of the beans in the application context form a cycle: ...

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans.

解决方案1

添加-Dspring.main.allow-circular-references=true到Application启动命令中

这种方式的原理是通过反射调用主类 SpringApplication的setAllowCircularReferences方法

解决方案2

添加@Lazy注解到其中一个自动注入的属性 例如:

@Component
public class BeanA {

    @Autowired
    @Lazy
    private BeanB beanb;

}