Dependency Injection is a design pattern in software engineering that allows for the creation of loosely coupled components in an application. It is a technique where the dependencies required by an object are provided externally rather than created within the object itself. In other words, instead of an object creating its own dependencies, it receives them from an external source. main benefit of Dependency Injection is that it promotes modularization and extensibility of code. By separating the creation and use of dependencies, it allows components to be developed and tested in isolation, and it makes it easier to switch out one implementation of a dependency for another.
Types of Dependency Injection:
There are three types of Dependency Injection:
Constructor Injection : dependencies are passed to the constructor of the object when it is created.
Eg:
public class MyService {
private final MyRepository repository;
public MyService(MyRepository repository) {
this.repository = repository;
}
}
Setter Injection : Dependencies are set using setter methods after the object has been created.
Eg :
public class MyService {
private MyRepository repository;
public void setRepository(MyRepository repository) {
this.repository = repository;
}
}
Field Injection: Dependencies are directly injected into fields of the object using annotations.
Eg :
public class MyService {
@Autowired
private MyRepository repository;
}