Spring Setter Dependency Injection

In setter dependency injection, the IoC container injects a component’s dependencies via JavaBean-style setter methods. A component’s setters expose the dependencies the IoC container can manage. The following code sample shows a typical setter dependency injection–based component:

public class SetterInjection {
    private Dependency dependency;
    public void setDependency(Dependency dependency) {
        this.dependency = dependency;
    }
    @Override
    public String toString() {
        return dependency.toString();
    }
}
An obvious consequence of using setter injection is that an object can be created without its dependencies, and they can be provided later by calling the setter.
Within the container, the dependency requirement exposed by the setDependency() method is referred to by the JavaBeans-style name, dependency. In practice, setter injection is the most widely used injection mechanism, and it is one of the simplest IoC mechanisms to implement.

Comments