The dependencies of some of the beans in the application context form a cycle
1. 异常信息
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2025-06-07 17:18:57.631 ERROR 68444 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : ***************************
APPLICATION FAILED TO START
***************************Description:The dependencies of some of the beans in the application context form a cycle:┌─────┐
| getDataSource defined in com.GenerateDatabaseDocumentApplication
└─────┘Process finished with exit code 1
这是一个典型的 Spring 应用启动失败 错误,错误类型为:
❌ Bean 循环依赖问题(Circular Dependency)
日志关键信息
The dependencies of some of the beans in the application context form a cycle
getDataSource defined in GenerateDatabaseDocumentApplication
这表示 Spring 容器在初始化 Bean 的过程中检测到了循环依赖。
📌 常见原因分析
- 构造函数注入导致的循环依赖
- Spring 无法处理构造器注入方式下的循环依赖(Setter 注入可处理)。
- 配置类中定义的 Bean 存在相互依赖
- 比如:
Bean A
依赖Bean B
,而Bean B
又依赖Bean A
。
- 比如:
- @Primary、@Qualifier 使用不当
- 数据源 Bean ([getDataSource](file://com/zaxxer/hikari/HikariConfig.java#L80-L80)) 和其他组件之间形成依赖闭环
✅ 解决方案
方案一:检查并重构代码中的依赖关系
查看以下内容是否存在互相引用:
- [GenerateDatabaseDocumentApplication]方法
- 数据库相关配置类或 DAO 层是否直接/间接依赖了包含 [getDataSource()](file://com/zaxxer/hikari/HikariConfig.java#L80-L80) 的类
🔍 示例:
@Bean
public DataSource getDataSource() {return dataSource; // 如果 dataSource 是通过构造函数注入的,并且指向另一个 Bean,可能造成循环
}
方案二:改用 Setter 注入 或 @Lazy
使用 @Lazy
延迟加载其中一个 Bean
@Autowired
@Lazy
private SomeService someService;
这样可以打破循环依赖链。
方案三:使用 ApplicationContext
手动获取 Bean(避免直接注入)
@Component
public class MyComponent {@Autowiredprivate ApplicationContext context;private SomeService someService;@PostConstructpublic void init() {someService = context.getBean(SomeService.class);}
}
方案四:启用 Debug 输出查看完整依赖链条
运行时加上 --debug
参数:
java -jar your-app.jar --debug
输出中会显示完整的循环依赖链,帮助定位具体是哪些 Bean 造成的循环。
🧪 推荐排查步骤
- 查看完整的日志输出,尤其是
APPLICATION FAILED TO START
下面列出的循环路径。 - 检查 [getDataSource()]是否被多个 Bean 引用,并构成循环。
- 使用 IDE 分析 Bean 之间的依赖关系(IntelliJ 支持 Spring Bean 图形化展示)。
- 尝试简化 Bean 创建逻辑或拆分配置类。