4/08/2016

Circular dependency injection in spring

Circular dependency injection is not possible in spring,lets see why its not possible. Lets say i have two classes class A and class B, In class A, class B is auto wired and in class B, class A is auto wired.

class A  
{
 @Autowired 
   B instanceOfB
  }
 class B {
  @Autowired
   A instanceOfA
   }
When spring container starts, lets assume class A loading first in the container. When spring initialize the class A it finds dependency of B ,so the container try to create a instance of B and inject into A. Now when its try to create a instance of B,again it finds an dependency to A so the control goes to create a instance of A. Final outcome is recursive and we will not be able to achieve this. How to overcome this
alt
There is no direct solution to achieve this but we have an work around for this issue.  Lets keep the class A as it is, but we need to make little bit changes in class B.We need to inject spring context in class B by implementing the interface ApplicationContextAware. So now class A instance is created without any issues. Now in class B we have method annotated with PostContruct and what this annotation does is initializeB method is get called after instance of B is created. In this method we are initializing class A,now both classes have the instance of other class. This way we can achieve the circular dependency in spring.

class A  
{
 @Autowired
   B instanceOfB 
  } 
class B implements ApplicationContextAware{
 private ApplicationContext applicationContext;   
 public void setApplicationContext(ApplicationContext applicationContext) {
  this.applicationContext = applicationContext; 
 }     
 @PostContruct
 public void initialiseA()
 {
   Class A = applicationContext.getBean("ClassA");
  }
  }

CommentsComments