Dependency Injection (DI) is a software design pattern that promotes loose coupling between the components of an application by allowing components to be loosely coupled and only dependent on abstractions, removing the need for them to be dependent on each other.
In simple terms, DI allows one object to be supplied to another object, which requires it for its functionality. This approach enables better decoupling between classes, making them more maintainable, testable, and reusable.
Spring offers three types of Dependency Injection or IOC:
1. Constructor-based DI: Spring injects dependencies through a constructor. It requires that all required dependencies be available when an object is created. This approach is particularly useful when the object being created requires several dependencies to work.
Example:
public class MyController {
private final MyService myService;
public MyController(MyService myService) {
this.myService = myService;
}
// methods
}
2. Setter-based DI: Spring uses the setter method to inject dependencies into an application. Setter-based DI is suitable for optional dependencies that can have a default or no value.
Example:
public class MyController {
private MyService myService;
public void setMyService(MyService myService) {
this.myService = myService;
}
// methods
}
3. Field-based DI: In this approach, Spring injects dependencies directly into fields, which eliminates the need for setter methods or constructors. Field-based DI is suitable for small applications and allows for a cleaner and less verbose code.
Example:
public class MyController {
@Autowired
private MyService myService;
// methods
}
Overall, Spring’s Dependency Injection offers different options for configuring and managing dependencies, depending on the requirements of each component. It allows for flexible and modular app development, promoting easy testing and maintenance.