Spring. Use Java configuration to resolve circular dependencies without @ Autowired
I have circular dependency and Java configuration Although it is easy to solve it with XML configuration, I can't solve it without @ Autowired. XML configuration Beans:
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; public A getA() { return a; } public void setA(A a) { this.a = a; } }
I have tried (I have read the @ bean annotation. Spring will not call methods every time the bean is referenced, but in this case, it is actually called all the time):
@Configuration public class Config { @Bean public A a() { A a = new A(); a.setB(b()); return a; } @Bean public B b() { B b = new B(); b.setA(a()); return b; } }
Moreover, use the configuration class field of @ Autowired:
@Configuration public class Config { @Autowired A a; @Autowired B b; @Bean public A a() { A a = new A(); a.setB(b); return a; } @Bean public B b() { B b = new B(); b.setA(a); return b; } }
In addition, I have tried all the above with @ lazy annotation No help, but if I annotate the setters of a and B with @ Autowired, the effect will be very good But that's not what I want now What did I do wrong? Is there a way to solve the circular dependency without using @ Autowired in Java configuration?
Solution
The behavior you want is as follows
A a = new A(); B b = new B(); a.setB(b); b.setA(a);
@Bean method doesn't give you They run complete to provide a bean instance
You basically have to partially create an instance and then complete initialization when you create another instance
@Configuration class Config { @Bean public A a() { A a = new A(); return a; } @Bean public B b() { B b = new B(); A a = a(); b.setA(a); a.setB(b); return b; } }
or
@Bean public B b(A a) { B b = new B(); b.setA(a); a.setB(b); return b; }