Introduction
Dependency Injection (DI) is a design pattern used to achieve loose coupling between classes. Instead of a class creating its own objects, the required objects (dependencies) are provided by an external container. In Spring Boot, the Spring Container automatically creates and injects objects into classes.
What is Dependency Injection?
Dependency Injection is a process where the Spring Framework provides the required object to a class instead of the class creating the object itself using the new keyword. This makes the application more flexible, maintainable, and easier to test.
Without Dependency Injection
public class Car {
Engine engine = new Engine(); // Object created manually
}
In this approach, the Car class is tightly coupled with the Engine class.
With Dependency Injection
@Component
public class Engine {
}
@Component
public class Car {
@Autowired
private Engine engine;
}
Here, Spring creates the Engine object and injects it into the Car class automatically.
What is @Autowired in Spring Boot?
@Autowired is an annotation used for Dependency Injection in Spring.
It tells the Spring Container:
"This class needs an object of another class. Please create it and inject it automatically."
What happens here?
=> Spring starts the application.
=> It finds @Component on Engine.
=> Spring creates an Engine object and stores it in the Spring Container.
=> It finds @Autowired on engine.
=> Spring injects the already created Engine object into the Car class.
Internally, it works like:
Engine engine = new Engine();
Car car = new Car();
car.engine = engine;
--> But Spring does this automatically.
Why Do We Use Dependency Injection?
=> Reduces tight coupling between classes.
=> Improves code maintainability.
=> Makes unit testing easier.
=> Promotes code reusability.
=> Helps manage object creation automatically.
Top comments (0)