由于,我想精简控制层代码,把控制层的大量代码都写入了服务层,然后有一个需要逻辑维护的外键,导致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解决方案