Dependency Injection in Spring Boot
What is Dependency Injection?
Injecting dependency to the class from outside (External service - Spring Container).
Why Dependency Injection?
We want to achieve loose coupling.
How we will do Dependency injection in Spring and Spring boot?
Spring: we will create an external XML file (let's say bean.xml) and from XML we will inject dependencies.
Spring Boot: write the annotation @Component above the dependent class by writing @component above any class we are making that class component of spring framework, the class which wants the object of the dependent class has to mention @Autowired above the object reference.
Ex.
@Components
class HitachiHD implements HardDrive{............}
class Laptop{
@Autowired
HardDrive obj;
}
ScreenShot
Car Interface
Alto car as Spring Component
Autowire with Spring IoC
Benefits of Dependency injection:
1. Loose coupling
2. Easy unit testing
No comments:
For Query and doubts!