【Spring循环依赖报错】The dependencies of some of the beans in the application context form a cycle

本文介绍了Spring框架中出现循环依赖错误的情况,并提供了详细的错误信息。分析了循环依赖产生的原因,包括两个类相互依赖的情况。最后给出了两种解决方案:一是通过代码解耦来避免循环依赖;二是使用@Lazy注解来延迟加载其中一个Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【Spring循环依赖报错】The dependencies of some of the beans in the application context form a cycle


一、报错信息


***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

   categoryController (field private com.vector.service.ICategoryService com.vector.controller.CategoryController.ICategoryService)
      ↓
   categoryService (field private com.vector.service.IArticleService com.vector.service.impl.CategoryServiceImpl.articleService)
┌─────┐
|  articleServiceImpl (field private com.vector.service.IUserService com.vector.service.impl.ArticleServiceImpl.iUserService)
↑     ↓
|  userServiceImpl (field private com.vector.service.IArticleService com.vector.service.impl.UserServiceImpl.iarticleService)
└─────┘




二、分析原因

       类A需要通过构造函数注入的类B的实例(或者B中声明的Bean),而类B需要通过构造函数注入的类A的实例(或者A中声明的Bean),导致循环依赖注入。


三、解决方案

解决方案一

其中一个不要引用对方,避免循环依赖,代码解耦肯定是最优解。

解决方案二

选择其中一个使用@Lazy 注解。

 @Autowired
 @Lazy
 private IArticleService articleService;

       延迟互相依赖的其中一个bean的加载,从而解决Spring在初始化bean的时候不知道先初始化哪个的问题。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慢热型网友.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值