Circular dependencies are the scenarios when two or more beans try to inject each other via constructor.
Let's consider following two classes (outside of Spring framework):
class Driver {
public Driver(Car car) {
}
}
class Car {
public Car(Driver driver) {
}
}
How we are going to initialize above two classes via constructor? Let's try.
public class Test {
public static void main(String[] args) {
Car car = new Car( );// how we going to supply driver's instance here?
Driver driver = new Driver(car);
}
}
It's not possible to write a compilable code which can initialize exactly one instance of each Car and Driver, and pass to each other's constructor. We can, however, refactor our above code and can pass circular references via setters but that would kill the semantics of 'initializing mandatory final fields via constructors.
The same problem Spring faces when it has to inject the circular dependencies via constructor. Spring throws BeanCurrentlyInCreationException in that situation. Let's see some examples.
Example of circular dependencies in Spring
Beans
package com.logicbig.example;
import org.springframework.stereotype.Component;
@Component
public class Car {
private final Driver driver;
public Car(Driver driver) {
this.driver = driver;
}
}
package com.logicbig.example;
import org.springframework.stereotype.Component;
@Component
public class Driver {
private final Car car;
public Driver(Car car) {
this.car = car;
}
}
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ComponentScan
@Configuration
public class ExampleMain {
public static void main(String[] args) {
new AnnotationConfigApplicationContext(ExampleMain.class);
}
} OutputCaused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'car': Requested bean is currently in creation: Is there an unresolvable circular reference?
In next examples, we will see how to avoid BeanCurrentlyInCreationException .
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 4.3.0.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|