What are the types of Dependency Injection?
Types of Dependency Injection
Dependency Injection is a popular design pattern in software engineering that is used to reduce the coupling between different parts of an application. There are three types of dependency injection: Constructor Injection, Setter Injection, and Interface Injection.
1. Constructor Injection
Constructor injection is the most common and simplest form of dependency injection. In this method, the dependencies are provided to the class through its constructor. The class that owns the dependencies constructs them by using a constructor parameter. This method ensures that the class has all its dependencies available when it is created.
public class MyClass {
private MyDependency myDependency;
public MyClass(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
2. Setter Injection
Setter injection is another type of dependency injection. In this method, the dependencies are provided to the class through setter methods. The class that owns the dependencies provides them by invoking a setter method on the class. This method is more flexible than constructor injection because you can set the dependencies after the class has been created.
public class MyClass {
private MyDependency myDependency;
public void setMyDependency(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
3. Interface Injection
Interface injection is less common than the other two methods of dependency injection. In this method, the dependent object implements an interface that defines methods to set the dependencies. The class that owns the dependencies provides them by invoking the methods defined in the interface. This method is more complex than the other two methods of dependency injection but can be useful in certain situations.
public interface MyInterface {
public void setMyDependency(MyDependency myDependency);
}
public class MyClass implements MyInterface {
private MyDependency myDependency;
public void setMyDependency(MyDependency myDependency) {
this.myDependency = myDependency;
}
}