Cyclic dependency
When using spring, you may encounter cyclic dependencies if you are primarily using a dependency injection, and in short, constructors that depend on 基于构造器
Bean A
Bean B
it Bean B
Bean A
. In this case, spring will be thrown at compile time BeanCurrentlyInCreationException
.
Class A
@Componentpublicclass ClassA { private ClassB classB; @Autowired publicClassA(ClassB classB) { this.classB = classB; } publicvoidprintClass() { System.out.println("Class A = "this); System.out.println("Class B = " + classB); }}
Class B
@Componentpublicclass ClassB { private ClassA classA; @Autowired publicClassB(ClassA classA) { this.classA = classA; } publicvoidprintClass() { System.out.println("Class A = " + classA); System.out.println("Class B = "this); }}
Test
@ContextConfiguration(classes = {ClassA.class, ClassB.class})@RunWith(SpringRunner.class)publicclass MyTest { @Autowired private ClassA classA; @Autowired private ClassB classB; @Test publicvoidname() { classA.printClass(); classB.printClass(); }}
Reason
Running the test at this time will find that the exception was thrown BeanCurrentlyInCreationException
. The reason for this is thatwhen spring creates the bean, it instantiates the object first and then injects the dependency . Assuming spring is created first, it will Class A
find dependencies in the constructor, Class B
so it will go to create Class B
, and in Class B
the constructor find the Class A
dependency, and this Class A
is not initialized, and therefore will be transferred to create Class A
, So we get into a dead loop.
Workaround
Replace 基于setter
the dependency injection to solve this problem. Because 基于setter
the dependency injection will first call the default constructor to instantiate the object, and then invoke the setter
implementation dependency injection. This way, there is no dependency at the stage of object instantiation, so the Class A
instantiation is completed and then called Class B
, and when the instantiation is complete, Class B
the value is set, and Class A
it is already instantiated, so it can be successfully referenced Class A
.
Circular dependencies in spring