How to configure Circular dependencies in Spring

Suppose you have a scenario like this :

you have a class A which requires an instance of class B and class B requires instance of class A . So this is called circular dependencies and you are configuring this using constructor injection like this :

Eg:

public class A {	
	private B b;	
	
	public A(B b){
        this.b=b;
       }		
}

public class B {
	
	private A a;
	private int age;
	
	public B(A a, int age){
        this.b=b;
        this.age=age;
       }
	public void show(){
		 System.out.println("vaue of age is "+age);
	}

}

And configuration will be like this :

When you will try to run this program, it will throw BeanCurrentlyInCreationException.

One possible solution to this issue is to edit the source code of some of your classes to be configured via setters instead of via constructors. Another solution is not to use constructor injection and stick to setter injection only.

Solution :

public class A {
	
	private B b;	
	
	

	public B getB() {
		return b;
	}

	public void setB(B b) {
		this.b = b;
	}
	
}

public class B {
	
	private A a;
	private int age;
	
		
	public A getA() {
		return a;
	}

	public void setA(A a) {
		this.a = a;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public void show(){
		 System.out.println("vaue of age is "+age);
	}

}

Configuration will be like this.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

       <bean id="a" class="study.spring.beans.A">
       <property name="b" ref="b"></property>        
       </bean>
       
       
       <bean id="b" class="study.spring.beans.B">
        <property name="a" ref="a"></property>
        <property name="age" value="24"></property>
       </bean>

</beans>

Enjoy Coding….

Thanks

Bhupendra Pratap Singh

Having 4+ years of experience in java technology. Worked with various java and J2EE technology like jsp,servlet,struts,spring,ajax, web services,jquery. Hand on experience in BI with QlikView tool.If you wanna give feedback or something contact on [email protected]

More Posts - Website