Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomness in Spring Bean creation when there is circular bean dependency

Our application uses extensively uses Spring Beans, we randomly see application startup error saying that there is Circular Bean Dependency. But this error doesn't occur always, but is instead random across multiple restarts. What could be the reason for randomness here ? If there is a Circular Dependency why it doesn't consistently fail / succeed ?

Exception: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘x’: Requested bean is currently in creation: Is there an unresolvable circular reference?

like image 542
Ashish Anant Saxena Avatar asked Jun 13 '16 16:06

Ashish Anant Saxena


1 Answers

Spring starts the process of initializing beans and gets to know of Circular reference in the process. Depending on whether constructor based or member based auto wiring is used, circular reference may or may not be successful. If two classes involved in Circular Dependency Chain uses Constructor autowiring or member autowiring below scenarios could occur :

  1. Construtor Autowiring + Constructor Autowiring = Bean initialization will always fail
  2. Constructor Autowiring + Member Autowiring = Failure dependent on initialzation order (which could be random) a. If Bean having Constructor autowiring is first initialized, bean initialization will fail. b. If Bean having Member autowiring is first initialized, bean initialization will succeed.
  3. Member Autowiring + Member Autowiring = Bean initialization will always succeed even with Circular Dependency

So, if you have Circular Dpendency and autowiring falls in category (2), you may observe randomly succeeding / failing circular dependency resolution.

like image 77
Ashish Anant Saxena Avatar answered Sep 19 '22 17:09

Ashish Anant Saxena