一、报错信息
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
mqttConfig (field private com.awei.mqtt.MqttAcceptClient com.awei.config.MqttConfig.mqttAcceptClient)
┌─────┐
| mqttAcceptClient (field private com.awei.mqtt.MqttAcceptCallback com.awei.mqtt.MqttAcceptClient.mqttAcceptCallback)
↑ ↓
| mqttAcceptCallback (field private com.awei.mqtt.MqttAcceptClient com.awei.mqtt.MqttAcceptCallback.mqttAcceptClient)
└─────┘
二、解决方式
报错原因
两个类相互引用对方,导致Spring在初始化bean的时候不知道先初始化哪个,从而形成循环依赖注入。
解决方法
1、其中一个不要引用对方,避免循环依赖,代码解耦肯定是最优解。
2、任选其中一个使用@Lazy 注解。
延迟互相依赖的其中一个bean的加载,从而解决Spring在初始化bean的时候不知道先初始化哪个的问题。
@Autowired
@Lazy
private MqttAcceptClient mqttAcceptClient;
问题解决!