This example shows how use circular dependencies without having BeanCurrentlyInCreationException in Spring by using setter injection.
BeanCurrentlyInCreationException
package com.logicbig.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Car { private Driver driver; @Autowired public void setDriver(Driver driver) { this.driver = driver; } public void drive() { System.out.println("driven by: " + driver); } }
package com.logicbig.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Driver { private Car car; @Autowired public void setCar(Car car) { this.car = car; } public void showCar() { System.out.println("my car: " + car); } }
package com.logicbig.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import jakarta.annotation.PostConstruct; @ComponentScan @Configuration public class ExampleMain { @Autowired private Car car; @Autowired private Driver driver; @PostConstruct public void postConstruct() { car.drive(); driver.showCar(); } public static void main(String[] args) { new AnnotationConfigApplicationContext( ExampleMain.class); } }
driven by: com.logicbig.example.Driver@7ade5c73my car: com.logicbig.example.Car@29859c08
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.