Sobes.tech
Junior

What is the difference between dependency injection via constructor and via setter?

sobes.tech AI

Answer from AI

Difference in timing of implementation, dependency obligation, and capabilities when creating an object:

Feature Constructor Injection Setter Injection
Implementation Time At object creation. After object creation.
Obligation Dependency is mandatory for object creation. Dependency is optional.
Object State Object is created fully initialized. Object can be created in a partially initialized state.
Immutability Allows creating an object with immutable dependencies. Dependencies can be changed after object creation.
Number of Dependencies Better suited for a small number of dependencies. More convenient with a large number of optional dependencies.
Cyclic Dependencies Signals problematic cyclic dependencies. May hide cyclic dependencies.

Constructor injection is preferable for mandatory dependencies, ensuring object integrity from the moment of creation and allowing immutability.

// Example of constructor injection
public class ServiceA {
    private final DependencyB dependencyB;

    public ServiceA(DependencyB dependencyB) {
        this.dependencyB = dependencyB;
    }

    // ... methods using dependencyB
}

Setter injection is suitable for optional dependencies or when flexibility in changing dependencies after object creation is required.

// Example of setter injection
public class ServiceC {
    private DependencyD dependencyD;

    public void setDependencyD(DependencyD dependencyD) {
        this.dependencyD = dependencyD;
    }

    // ... methods using dependencyD (with null check if dependency is optional)
}
What is the difference between dependency injection… - sobes.tech