1.4 KiB
1.4 KiB
Getting started
Dependency injection https://www.youtube.com/watch?v=J1f5b4vcxCQ : Dependeny injection, the best pattern
Dependency
- there r functions or objects that use other objects or functions and they r called dependency. There are 2 types of coupling.
- Hard coupling: Here dependency cant be changed
- Loose coupling: To change dependency in future
Dependency injection
- Instead of instantiating new code in constructor or function in same braces/scope we pass it instead through parameter to be used.
- Main goal of dependency injection is to achieve loose coupling. eg without DI(Dependency Injection)
public class Laptop{
HardDrive obj1 = new HitachiHD();
}
with DI
public class Laptop{
HardDrive obj1;
Laptop(HardDrive obj){
this.obj1= obj;
}
}
- It is possible using external service. That service is responsible for creating objects.
- Example in spring boot
class Laptop{
@Autowired
HardDrive obj1;
}
@Component
class HitachiHD implements HardDrive{
// ...
}
With this @Autorired annotation it will find the component which is tagged by @Component to connect to it.
- Not only this is useful to prevent tight coupling, but also for testing. When we wanna test laptop then we may not need to check harddrive bcz it is already tested so with these we can separate it too. We can create mock object of the class if it is loosely coupled.