目录:
Spring - 循环依赖
-
Java循环依赖指的是两个或多个类之间的相互依赖,形成了一个循环的依赖关系,这会导致程序编译失败或运行时出现异常。
@Component
public class A {
@Autowired
B b;
}
@Component
public class B {
@Autowired
A a;
}
报错:
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| a (field com.example.demo.B com.example.demo.A.b)
↑ ↓
| b (field com.example.demo.A com.example.demo.B.a)
└─────┘
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.
-
在配置文件中放开循环依赖限制
application.properties
spring.main.allow-circular-references = true
-
代码层面:
- 把依赖的方法,直接写在本类中
- 添加一个中间类, 中间类去依赖A\B,然后让中间类去阻止他们的依赖方法。
-
延迟注入:
-
添加需要依赖的构造函数
-
添加
@Lazy
注解@Component public class A { B b; @Lazy public A(B b) { this.b = b; } } @Component public class B { @Autowired A a; }
-