Deep understanding of circular dependencies in spring

Cyclic dependence

Definition: circular dependency refers to circular reference, that is, two or more beans hold each other. For example, circularitya refers to circularityb, circularityb refers to circularityc, and circularityc refers to circularitya. Form a circular reference relationship.

When using spring, if you mainly use the constructor based dependency injection method, you may encounter circular dependency. In short, the constructor of bean a depends on bean B, and the constructor of bean B depends on bean a. In this case, spring will throw a beancurrentyincreationexception at compile time.

Class A

Class B

test

reason

At this time, running the test will find that a beancurrentyincreationexception exception is thrown. The reason for this is that when spring creates a bean, it will first instantiate the object and then inject dependencies. If spring first creates class A, it will find that there is a dependency on class B in the constructor, so it will turn to create class B, and it will find a dependency on Class A in the constructor of class B. at this time, class A has not been initialized, so it will turn to create class a, which will fall into an endless loop.

resolvent

This problem can be solved by using setter based dependency injection. Because setter based dependency injection will first call the default constructor to instantiate the object, and then call setter to implement dependency injection. In this way, there is no dependency in the object instantiation stage. Therefore, class a will call class B after the instantiation is completed. After the instantiation of class B is completed, the value will be set. At this time, class A has been instantiated, so class a can be referenced successfully.

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>