Dependency Injection
What is Dependency Injection?
Each Object-oriented application consists of many classes that work together in order to solve a problem. However, when writing a complex application, application classes should be as independent as possible. DI helps in gluing these classes together and at the same time keeping them independent. Dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object.
Pros
- increase the possibility to reuse classes
- test them independently of other classes while unit testing
Code with no DI vs code with DI
public class Computer {
private CPU cpu;
public Computer() {
this.cpu = new CPU();
}
}
Dependency between Computer and CPU.
public class Computer {
private CPU cpu;
public Computer(CPU cpu) {
this.cpu = cpu;
}
}
Dependency between Computer and CPU. Dependency is injected through class constructor (Computer should not worry about CPU implementation).
Types of DI
- Constructor-based dependency injection – used for mandatory dependencies
public Computer(CPU cpu) {
this.cpu = cpu;
}
- Setter-based dependency injection – used for optional dependencies
public Computer(CPU cpu) {
this.cpu = cpu;
}
- Property-based dependency injection – considered as bad practice!
@Autowired
private CPU cpu;
Letzte Beiträge
Share :
Share :
Weitere Beiträge
Dependency Injection with Spring 5
As we learned in the previous chapter dependency injection is a very powerful technique. DI is provided by the Spring 5 Framework implementation of the Inversion of Control (IoC) principle.
Room. Reactive queries
Room has great integration with LiveData. Results from SQL queries can be easily wrapped in LiveData container. This way LiveData can be observed in the UI. When the data is changed in the database, all active observers get notified and update the corresponding views.
Missing Authorization header in Angular 7 HTTP response
Accessing an API back-end from Angular client may result in missing response headers. A common scenario is a missing Authorization header, containing the JSON Web Token (JWT) which is returned from the back-end service when the user logs in successfully.