What are the different types of Dependency Injection in Spring?

In the Spring Framework, DI is used to satisfy the dependencies between objects. It exists in two major types:

Constructor Injection: Constructor-based DI can be accomplished by invoking the parameterized constructor. These constructor arguments will be injected during the instantiation of the instance.
Example:
public class ConstructorInjection {
    private Dependency dependency;
    public ConstructorInjection(Dependency dependency) {
        this.dependency = dependency;
    }
    @Override
    public String toString() {
        return dependency.toString();
    }
}

Setter Injection: Setter-based DI is the preferred method of Dependency Injection in Spring that can be accomplished by calling setter methods on your bean after invoking a no-argument static factory method or no-argument constructor to instantiate this bean.
Example:
public class SetterInjection {
    private Dependency dependency;
    public void setDependency(Dependency dependency) {
        this.dependency = dependency;
    }
    @Override
    public String toString() {
        return dependency.toString();
    }
}

References



Comments