【Spring循环依赖的解决】The dependencies of some of the beans in the application context form a cycle

【Spring循环依赖的解决】The dependencies of some of the beans in the application context form a cycle

1.报错信息

2.问题描述

启动报错: The dependencies of some of the beans in the application context form a cycle:

3. 报错原因

两个类相互引用对方,导致Spring在初始化bean的时候不知道先初始化哪个,从而形成循环依赖注入。
类A依赖类B,类B也依赖类A,这种情况就会出现循环依赖。

Bean A → Bean B → Bean A

上面是比较容易发现的循环依赖,也有更深层次的循环依赖。

Bean A → Bean B → Bean C → Bean D → Bean E → Bean A

4. 解决办法

方法1:代码解耦

根据报错的提示重新设计类的依赖,让其中一个类不要引用对方,避免循环依赖

方法2: @Lazy注解

不使用基于构造函数的依赖注入
在字段上使用@Autowired注解,让Spring决定在合适的时机注入。
用基于setter方法的依赖注射取代基于构造函数的依赖注入来解决循环依赖。
在@Autowired注解上方加上@Lazy注解(延迟加载)

两种办法都可以解决循环依赖的问题。

转载请说明出处内容投诉
CSS教程_站长资源网 » 【Spring循环依赖的解决】The dependencies of some of the beans in the application context form a cycle

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买