what is dependency injection in spring
Dependency injection in Spring means Spring creates your objects and supplies the other objects they need, instead of your classes creating those dependencies themselves. In practice, that makes code easier to test, swap, and maintain because the wiring happens outside the class.
What it means
A dependency is just another object a class uses. For example, a UserService
might depend on a UserRepository. With dependency injection, UserService
does not call new UserRepository() directly; Spring provides it.
Why Spring uses it
Spring uses DI to promote loose coupling. That means classes know less about how their collaborators are built, which makes the app more flexible and easier to test with mocks.
Main styles
- Constructor injection: dependencies are passed through the constructor.
- Setter injection: dependencies are set after object creation through setter methods.
- Field injection: Spring writes directly into a field, often using annotations.
Simple example
If OrderService needs PaymentGateway, constructor injection looks like
this idea:
- Spring creates
PaymentGateway. - Spring creates
OrderService. - Spring passes
PaymentGatewayintoOrderService.
So OrderService focuses on business logic, not on building its own
dependencies.
Spring benefit
Spring’s container manages bean creation and injection automatically, which is the core of how Spring applications are wired together.
TL;DR: Dependency injection in Spring is the framework handing your objects the things they need, rather than having them build those things themselves.