What is dependency injection in Spring?
Dependency injection is a pattern where an object receives the other objects it needs from the outside rather than creating them itself. In Spring, the framework creates and supplies these dependencies for you, which is a form of inversion of control. This makes code loosely coupled, easier to test, and easier to change.
The idea
Instead of a class building its own helpers with new, it declares what it needs and Spring hands those in. Spring manages these objects, called beans, in a container and wires them together automatically.
@Service
class OrderService {
private final PaymentService payment;
OrderService(PaymentService payment) { // injected by Spring
this.payment = payment;
}
}
Why it helps
- Loose coupling: classes depend on abstractions, not concrete creations.
- Testability: you can inject a fake dependency in tests.
- Flexibility: swap implementations without changing the class.
Prefer constructor injection over field injection in your answer, because it makes dependencies explicit and supports final fields and easy testing. Naming that preference signals real hands on experience.
Common follow up questions
Related interview questions
Want the full Spring Boot guide?
Read every Spring Boot concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the Spring Boot guide All Spring Boot questions