SpringBoot启动报 ------ The dependencies of some of the beans in the application context form a cycle错误

 今天在启动项目的时候遇见了这样一个报错,还挺稀奇的,百度后才发现挺常见的一个错误

Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

Description:

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

错误是:应用程序上下文中某些 Bean 的依赖关系形成一个循环

什么是依赖循环:

        现有一个ServiceA需要调用ServiceB的方法,那么ServiceA就依赖于ServiceB,那在ServiceB中再调用ServiceA的方法,就形成了循环依赖。Spring在初始化bean的时候就不知道先初始化哪个bean就会报错。

如何解决循环依赖 :

        对于代码中出现的耦合问题,解耦合的最好方法就是对现有的代码进行重构,当然我是没有选择进行重构的,因为方法要用,那这种情况下我们应该怎么做呢:

 

 解决方法一:

 
public class ClassA {
    @Autowired
    ClassB classB;
}
 
public class ClassB {
    @Autowired
    ClassA classA ;
}

 解决方法二:

spring:
    main:
        allow-circular-references: true

 解决方法三:

        不使用基于构造函数的依赖注入
        在字段上使用@Autowired注解,让Spring决定在合适的时机注入。
        用基于setter方法的依赖注射取代基于构造函数的依赖注入来解决循环依赖。
        在@Autowired注解上方加上@Lazy注解(延迟加载)

 解决方法四:

        代码重构,根据报错的提示重新设计类的依赖,让其中一个类不要引用对方,避免循环依赖

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值