Sobes.tech
Junior — Middle

How to correctly implement dependency injection if components A and B refer to each other, creating a cyclic dependency?

sobes.tech AI

Answer from AI

A cyclic dependency between components A and B occurs when A depends on B, and B simultaneously depends on A. To correctly implement dependency injection in such cases, several approaches can be used:

  1. Inversion of Control via interfaces: Introduce interfaces for components to break the direct dependency.

  2. Lazy initialization: Use lazy loading of dependencies to avoid cyclic calls during object creation.

  3. Injection via setters or methods: Instead of constructor injection, use setters to create objects without dependencies first, then set them.

An example using Spring and the @Lazy annotation:

@Component
public class A {
    private final B b;

    public A(@Lazy B b) {
        this.b = b;
    }
}

@Component
public class B {
    private final A a;

    public B(@Lazy A a) {
        this.a = a;
    }
}

Thus, Spring will create proxy objects and resolve the cyclic dependency without initialization errors.

How to correctly implement dependency injection if… - sobes.tech