SpringBoot 2.6.0 以上 @Autowired 没有解决循环依赖

使用@Autowired,仍在提示循环依赖,提示:
As a last resort, it may be possible to break the cycle automatically by setting 
 spring.main.allow-circular-references to true.

因为在2.6.0之前,spring会自动处理循环依赖的问题,2.6.0 以后的版本默认禁止 Bean 之间的循环引用,如果存在循环引用就会启动失败报错。

如何解决

清理循环引用的Bean
1、在字段上使用@Autowired注解,让Spring决定在合适的时机注入。
2、在@Autowired注解上方加上@Lazy注解(延迟加载)
在配置文件中设置,暂时跳过处理循环依赖:
spring:
  main:
    allow-circular-references: true
或者在main中设置:
public static void main(String[] args) {
    SpringApplication app = new SpringApplication(App.class);
    app.setAllowCircularReferences(Boolean.TRUE);
    app.run(args);
}
posted @ 2023-03-20 15:12  NetUSA  阅读(734)  评论(0)    收藏  举报