1

Suppose I have two classes

Class A

Class B

Now, Class A has dependency on Class B and Class B has dependency on class B.

Looks like

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

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

The bean configuration for the same will be

@Bean 
public A getA() {
return new A(getB());
}

@Bean 
public B getB() {
return new B(getA());
}

This code results in a deadlock situation as one depeneds on the other. How to instantiate Beans in such case?

malejpavouk
  • 4,297
  • 6
  • 41
  • 67
Rohit Mishra
  • 281
  • 5
  • 16

2 Answers2

1

Try using setter based dependency injection. Topic had also been discussed at Circular dependency in spring

Community
  • 1
  • 1
1

Other option is to use @PostConstruct annotation. In the answer proposed by Plog ypu have a problem that initialization of A is done in init method of B. With postConstruct, you can have a dedicated method resolveCircularDependencies.

Its just a cosmetic change, but makes it explicit why the wiring is done this way (which comes handy, when you forget about the existence of the cycle, or other programmer encounters the code).

@Bean 
public A getA(){
    return new A();
}

@Bean 
public B getB(){
    return new B();
}

@PostConstruct
public void resolveCircularDependencies() {
    getB().setA(getA());
    getA().setB(getB());
}
malejpavouk
  • 4,297
  • 6
  • 41
  • 67