To resolve circular bean references follow the following steps:
Step1: - Make default constuctor
Step2: - Use setter method for injecting bean.
For more you see the following example:
package com.circularBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanA{
private BeanB beanB;
public BeanA() {
}
@Autowired
public void setBeanB(BeanB beanB) {
this.beanB = beanB;
}
@Override
public String toString() {
return beanB.getClass().getSimpleName() + " from " + this.getClass().getSimpleName();
}
}
package com.circularBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanB {
private BeanA beanA;
public BeanB() {
}
@Autowired
public void setBeanA(BeanA beanA) {
this.beanA = beanA;
}
@Override
public String toString() {
return beanA.getClass().getSimpleName() + " from " + this.getClass().getSimpleName();
}
}
package com.circularBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class CircularBeanMain {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "resources/app-context.xml" });
BeanA beanA = applicationContext.getBean(BeanA.class);
BeanB beanB = applicationContext.getBean(BeanB.class);
System.out.println(beanA);
System.out.println(beanB);
}
}
Output:
BeanB from BeanA
BeanA from BeanB