解决 Spring Boot 报错 BeanCurrentlyInCreationException 循环依赖
分析 Spring Boot 2.6+ 默认禁用循环依赖后报 BeanCurrentlyInCreationException 的根因,提供 @Lazy 与设计解耦重构方案。
问题现象
升级至 Spring Boot 2.6+ 或重构代码后,应用启动失败:
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| orderService (field private com.example.PaymentService com.example.OrderService.paymentService)
↑ ↓
| paymentService (field private com.example.OrderService com.example.PaymentService.orderService)
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans.
触发根因
- Spring Boot 2.6+ 默认将
spring.main.allow-circular-references设为了false。 - 架构设计不合理,两个服务之间双向强依赖(Service A 依赖 Service B,Service B 又反向依赖 Service A)。
解决步骤与操作命令
步骤一:方案 A —— 架构重构解耦(最佳实践)
将共用的逻辑抽象抽离到第三个服务中(例如创建 OrderCommonService),消除双向依赖:
OrderService -> OrderCommonService
PaymentService -> OrderCommonService
步骤二:方案 B —— 使用 @Lazy 延迟加载注水
如果短期内来不及全面重构,在构造器或属性注入上添加 @Lazy 注解:
@Service
public class OrderService {
private final PaymentService paymentService;
public OrderService(@Lazy PaymentService paymentService) {
this.paymentService = paymentService;
}
}
步骤三:方案 C —— 在配置文件中临时放行(紧急过渡)
在 application.yml 中开启循环引用允许:
spring:
main:
allow-circular-references: true
验证确认
重新启动 Spring Boot 应用:
控制台打印 Started Application in ... seconds (process running for ...),循环引用死锁解除。


