What's Dependency Injection (DI)?
Dependency Injection (DI) is a design pattern that implements the principles of Inversion of Control (IoC) by providing an object with its required dependencies from an external source instead of having the object create or locate them on its own. This not only improves code maintainability, flexibility, and testability, but also follows the IoC concept of shifting control from the object to the external dependencies, thereby decoupling the object from its dependencies and promoting modularity
What is IoC?
Inversion of control (IoC) is a general concept that refers to a program or system where the control flow of a program is determined by a framework or container, rather than by the program itself. In Spring, IoC is achieved through dependency injection.
In Spring, there is an implementation known as the IoC container, which connects the dependencies, locates, and manages the life cycle of beans. The Spring IoC container is represented by ApplicationContext, which is responsible for creating, setting up, and putting together the beans mentioned. The container follows the instructions for which objects to create, configure, and assemble from the configuration metadata it reads.
What is Autowiring?
In the context of Spring, Autowiring can be used to implement Dependency Injection. When you enable Autowiring for a bean, the Spring framework will automatically resolve and wire the dependencies for that bean, using one of the DI techniques, such as Constructor-based, Setter-based, or Field-based Dependency Injection.
In other words, Autowiring is a way to simplify the process of implementing Dependency Injection in Spring. By using Autowiring, you can eliminate the need to explicitly specify the relationships between beans in the configuration file, allowing you to make changes to your code more easily.
In this example, we will use the @Autowired annotation to enable Autowiring in Spring.
The 3 types of Dependency Injection in Spring are:
- Constructor-based Dependency Injection: The dependencies are provided to an object via constructors.
public class MyService {
private MyDependency myDependency;
// constructor injection
@Autowired
public MyService(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
- Setter-based Dependency Injection: The dependencies are provided to an object via setter methods.
public class MyService {
private MyDependency myDependency;
@Autowired
public void setMyDependency(MyDependency myDependency) {
this.myDependency = myDependency;
}
}
- Field-based Dependency Injection: The dependencies are provided to an object via fields.
public class MyService {
@Autowired
private MyDependency myDependency;
}
Top comments (0)