There are three types of dependency injection:
- Constructor Injection(e.g. Spring): Dependencies are provided as constructor parameters.
- Setter Injection(e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
- Interface Injection(e.g. Avalon): Injection is done through an interface.
In advanced Java, especially in the context of frameworks like Spring, Inversion of Control (IoC) is often associated with the concept of Dependency Injection (DI). Dependency Injection is a specific type of IoC. There are two main types of IoC:
- Setter Injection:
- In Setter Injection, the container injects dependencies through setter methods of the client class.
- The client class must provide setter methods for each dependency, and the container uses these methods to inject the required dependencies.
Example in Spring:
java
// Setter method for dependency injectionpublic class MyService {
private MyDependency myDependency;
public void setMyDependency(MyDependency myDependency) {
this.myDependency = myDependency;
}
} - Constructor Injection:
- In Constructor Injection, the container injects dependencies through the constructor of the client class.
- The client class must have a constructor that accepts the required dependencies as parameters, and the container uses this constructor to inject the dependencies.
Example in Spring:
java
// Constructor for dependency injectionpublic class MyService {
private final MyDependency myDependency;
public MyService(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
These two types of dependency injection help achieve Inversion of Control, where the control of the flow of the program is inverted from the client to the container. The container manages the dependencies and injects them into the client class, reducing the tight coupling between components and making the code more modular and testable.