Spring Framework FAQ: Top Questions
12. How does Spring handle circular dependencies?
Spring can resolve circular dependencies between beans using setter injection. Constructor-based circular dependencies are not resolved automatically.
📘 Explanation:
- Setter injection: Spring creates proxies and injects dependencies post-instantiation.
- Constructor injection: Causes
BeanCurrentlyInCreationException
.
📥 Example:
public class A {
private B b;
public void setB(B b) { this.b = b; }
}
public class B {
private A a;
public void setA(A a) { this.a = a; }
}
🏆 Expected Output:
Spring injects A and B into each other using setter methods.
🛠️ Use Cases:
- Legacy code migration where cycles exist.
- Bidirectional relationships in domain models.