关于SpringBoot中出现的循环依赖问题
- 环境:
SpringBoot2.7.8
- 背景:
-
在增加出库订单时需要对物品表的的数量进行修改
-
Description:
The dependencies of some of the beans in the application context form a cycle:
┌──->──┐
| getGoodsNumber defined in class path resource [com/QRproject/project/system/controller/GoodsController.class]
└──<-──┘
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. - 代码:
- 在OutboundController中创建了个公共方法,并将其注入到Spring中:(以下方法均未开启事务支持)
-
1 @RestController 2 @RequestMapping("/goods") 3 public class GoodsController { 4 5 @Autowired 6 private IGoodsService goodsService; 7 @Bean 8 public boolean deleteGoodsNum(Integer goodsId,Integer goodsNum){ 9 Goods goods = goodsService.getById(goodsId); 10 goods.setGoodsNumber(goods.getGoodsNumber()-goodsNum); 11 goodsService.updateById(goods); 12 return true; 13 } 14 }
- 接着我在OutboundController中注入GoodsController
-
1 public class OutboundController { 2 @Autowired 3 private IOutboundService outboundService; 4 @Autowired 5 private GoodsController goodsController; 6 7 @PostMapping 8 public Result<?> addOutbound(@RequestBody Outbound outbound){ 9 goodsController.deleteGoodsNum(outbound.getGoodsId(),outbound.getGoodsNumber()); 10 LocalDateTime localDateTime = LocalDateTime.now(); 11 outbound.setOutTime(localDateTime); 12 outboundService.save(outbound); 13 return Result.success("增加出库订单成功"); 14 } 15 }
- 运行完便报错了
- 解决:
-
引发的原因是因为两个类进行了相互的调用,触发了spring的循环依赖检查
诚然造成循环依赖是一个bad habit 我们需要另外一种解决方法:
- 1.试着把goodsServices注入过来结果还是一样
- 2.使用@Lazy 懒加载注解 还是不行
-
1 @Lazy 2 @Autowired 3 private GoodsController goodsController;
- 3.试了一下在配置中开启循环依赖支持结果也不行。。
-
1 spring: 2 main: 3 allow-circular-references: true
- 4.最后只好老实敲代码进行解耦了
- goodsPublicService
-
1 @Service 2 public interface goodsPublicService extends IService<Goods>{ 3 void deleteGoodsNum(Integer goodsId, Integer goodsNumber); 4 }
- goodsPublicServiceImpl:
-
1 @Service 2 public class goodsPublicServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements goodsPublicService { 3 public void deleteGoodsNum(Integer goodsId,Integer goodsNum){ 4 Goods goods = this.baseMapper.selectById(goodsId); 5 goods.setGoodsNumber(goods.getGoodsNumber()-goodsNum); 6 this.baseMapper.updateById(goods); 7 } 8 }
- OutboundController:
-
1 @PostMapping 2 public Result<?> addOutbound(@RequestBody Outbound outbound){ 3 goodsPublicService.deleteGoodsNum(outbound.getGoodsId(),outbound.getOutNum()); 4 LocalDateTime localDateTime = LocalDateTime.now(); 5 outbound.setOutNum(outbound.getOutNum()); 6 outbound.setOutTime(localDateTime); 7 outboundService.save(outbound); 8 return Result.success("增加出库订单成功"); 9
- 成功运行!
本文来自博客园,作者:Lollipop_pro,转载请注明原文链接:https://www.cnblogs.com/CooperCode/p/17657952.html
posted on 2023-08-25 21:03 Lollipop_pro 阅读(1294) 评论(0) 编辑 收藏 举报