首页 > 技术文章 > the dependencies of some of the beans in the application context form a cycle

liyhbk 2021-01-04 16:29 原文

1.1 Bug场景:

1.1 启动Spring Boot项目时报循环依赖错误:The dependencies of some of the beans in the application context form a cycle


┌─────┐
| userServiceImpl defined in file [D:\liyh\pro_new\diich-ecology\diich-biz\diich-biz-core\out\production\classes\com\diich\biz\service\core\UserServiceImpl.class] ↑ ↓ | favoriteServiceImpl defined in file [D:\liyh\pro_new\diich-ecology\diich-biz\diich-biz-core\out\production\classes\com\diich\biz\service\core\FavoriteServiceImpl.class]
└─────┘

1.2 SpringBoot中自定义DataSource数据源时报循环依赖错误:The dependencies of some of the beans in the application context form a cycle

  
org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthIndicatorAutoConfiguration ┌─────┐
| dataSource ↑ ↓ | scopedTarget.dataSource defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class] ↑ ↓ | org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker └─────┘

2.1 Bug原因:

以两个对象的相互依赖为例:

从异常信息可以看出,这是循环依赖问题。这种通常会出现在两个类注入Bean时互相使用了构造函数注入对方。Spring IoC容器在运行时检测到此循环引用就会报错。

在SpringBoot多模块项目中,两个项目互相引入对方的依赖,就会报这样的错误。

3.1 解决方法:

1.在实例变量上使用@Autowired注解,让Spring决定在合适的时机注入,而非在初始化类的时候就注入。

2.用基于setter方法的依赖注入取代基于构造函数的依赖注入来解决循环依赖。

3.排除Spring Boot数据源自动配置类

// 自定义数据源一定要排除SpringBoot自动配置数据源,不然会出现循环引用的问题,The dependencies of some of the beans in the application context form a cycle
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})

4.在application.properties 文件中加入一行代码  

 spring.datasource.initialize=false

5.避免两个项目互相引入对方的依赖

 

推荐阅读