spring循环注入,The dependencies of some of the beans in the application context form a cycle

文章讲述了在Spring应用中遇到的循环依赖问题,具体表现为CategoryService和DishService之间的互相调用。解决方案包括设置spring.main.allow-circular-references=true允许循环注入,或者使用@Lazy注解来延迟初始化,避免在构建时形成闭环。文章提供了深入理解循环注入和@Lazy作用的资源链接。

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

        由于,我想精简控制层代码,把控制层的大量代码都写入了服务层,然后有一个需要逻辑维护的外键,导致2个服务层相互调用,产生了循环依赖。

***************************

Description:

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

   categoryController (field com.ywzs.service.CategoryService com.ywzs.controller.CategoryController.categoryService)
┌─────┐
|  categoryServiceImpl (field com.ywzs.service.DishService com.ywzs.service.impl.CategoryServiceImpl.dishService)
↑     ↓
|  dishServiceImpl (field com.ywzs.service.CategoryService com.ywzs.service.impl.DishServiceImpl.categoryService)
└─────┘


Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

看到这个提示就知道了,spring告诉我们需要添加一个配置来允许循环注入

setting spring.main.allow-circular-references : true.

其实还有另外几种解决方案,比如给要注入的循环引用的类加上@Lazy注解...等等

注意循环注入就是两个或两个以上的bean互相持有对方,最终形成闭环。

Spring构造器注入循环依赖的解决方案及原理探索 - 简书 (jianshu.com)感兴趣的可以去这篇文章看看,用例子来深入讲解循环注入的@Lazy解决方案

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值