1. 问题描述
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. 问题原因
以两个对象的相互依赖为例:
从异常信息可以看出,这是循环依赖问题。这种通常会出现在两个类注入Bean时互相使用了构造函数注入对方。Spring IoC容器在运行时检测到此循环引用就会报错。
在SpringBoot多模块项目中,两个项目互相引入对方的依赖,就会报这样的错误。
3. 解决方法
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 文件中加入一行代码
5. 避免两个项目互相引入对方的依赖
List of articles
- background
- error message
- solve
Here is weihubeats, Feel good about the official account. Minor technique , The article first . Reject marketing number , Reject the title party
background
Spring Boot Version by 2.4.2 Upgrade to 2.6.8 , Then start Discovery PageHelper Report errors
error message
- pagehelper-spring-boot-starter edition : 1.3.0
solve
Looking at the error message, it is obvious that there is a circular dependency , And found that Spring Boot 2.6 The above versions disable circular dependency by default . So there are two solutions
- Turn on circular dependency
This is not recommended , After all, circular dependencies are disabled , Therefore, circular dependency is not recommended . Nor should our code have circular dependencies
- upgrade pagehelper-spring-boot-starter edition
You can see pagehelper-spring-boot-starter The official new version solves this problem bug Of , So we upgrade pagehelper-spring-boot-starter Just go to the latest version