升级boot版本至2.6.x的更新之循环依赖

/ 技术收藏 / 没有评论 / 506浏览

前几天遇到一个问题,就是代码中产生了循环依赖,然后就报了以下异常

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.

依稀还记得,一般这种A依赖B,B又依赖A的这种循环,spring通过bean的三级缓存,提前暴漏对象的方式已经解决了啊。仔细又读了一下报错信息,它说把 spring.main.allow-circular-references 设置成true也可以作为解决手段, 从这个属性的字面意思也可以看到,要把允许循环依赖设置为true即可解决,那么应该是spring在2.6.x的版本默认不允许循环依赖了。

解决方法1: 可以在bean上加上@Lazy注解,让bean延迟加载

解决方法2: 按照提示信息,配置文件中添加

spring:
  main:
    allow-circular-references: true

当然如果能在业务层面较低成本打破循环依赖是最好的,如果成本较高,建议方案一。

如果既有代码升级boot版本,方案二也未尝不可。