Constructor dependency injection occurs when a component’s dependencies are provided to it in its constructor (or constructors). The component declares a constructor or a set of constructors, taking as arguments its dependencies, and the IoC container passes the dependencies to the component when instantiation occurs, as shown in the following code snippet:
public class ConstructorInjection {
private Dependency dependency;
public ConstructorInjection(Dependency dependency) {
this.dependency = dependency;
}
@Override
public String toString() {
return dependency.toString();
}
}
An obvious consequence of using constructor injection is that an object cannot be created without its dependencies; thus, they are mandatory.
Check out a complete example at Spring Dependency Injection via Constructor Example
Comments
Post a Comment