【Java异常】The dependencies of some of the beans in the application context form a cycle

本文目录

一、背景描述

二、问题原因

三、解决方案

3.1 方案1

3.2 方案2

 四、其他解决方案


一、背景描述

Springboot 2.1.5  + MybatisPlus 3.3.1

今天启动一个springboot项目时,竟然发现项目启动失败,提示信息如下:

Description:

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

   configDataFeignController (field private com.iot.basic.config.business.service.ConfigDataService com.iot.basic.config.controller.feign.configdata.ConfigDataFeignController.configDataService)
┌─────┐
|  configDataService defined in file [G:smarthome2项目代码	runk云端asic-iot-config(基础配置服务)asic-iot-configiot-config-business	argetclassescomiotasicconfigusinessserviceimplConfigDataServiceImpl.class]
↑     ↓
|  productConfigDataContentService defined in file [G:smarthome2项目代码	runk云端asic-iot-config(基础配置服务)asic-iot-configiot-config-business	argetclassescomiotasicconfigusinessserviceimplProductConfigDataContentServiceImpl.class]
└─────┘

仔细检查了这两个类,发现Bean的注入方式均为@AllArgsConstructor使用了基于构造器依赖注入的方式。下面就是项目中的代码截图:两个Java类中都是这样的写法

二、问题原因

问题产生的原因是 ServiceA实现类中引入了ServiceB,而在ServiceB实现类中又引入了ServiceA,导致循环依赖注入。

其实在代码开发过程中应该尽量避免这种操作的出现,即使再复杂的业务场景也不应该有这波操作。

知道以上原因了,那么就可以对症下药了。

三、解决方案

网上方案很多,网上的方式都是针对项目实际存在的问题的解决方案,不一定适合自己的项目,如果不懂,只有多试几种方法,总有一种适合自己的项目。

3.1 方案1

在ServiceA实现类中引入ServiceB,而ServiceB再引入ServiceC,避免循环依赖。在实际中应该使用这种方式,我比较懒,使用了方案2,本地测试使用。

3.2 方案2

比较懒的一种方式是,使用Spring@Autowired自动依赖注入方式成功解决这个问题。

 四、其他解决方案

顺带在网上也找了下别人的解决办法,总结起来有以下几种:

1、在字段上使用@Autowired注解,让Spring决定在合适的时机注入;
2、不要使用基于构造函数的依赖注入;
3、用基于setter方法的依赖注入;

以上方法仅供参考,一种方法不行可以多试几种方法。当然最根本解决方案还是要知道自己的项目代码为什么出错,根据问题对症下药才是解决方案的王者。

完结!

原文地址:https://www.cnblogs.com/no8g/p/13415478.html