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.
- Dependency injection means the framework supplies an object's dependencies instead of the object creating them.
- It reduces tight coupling and makes code easier to test.
- Spring manages this through its inversion of control container.
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.
Frequently asked questions
What is inversion of control?
It is the principle that a framework, not your code, controls object creation and wiring. Dependency injection is the most common way to apply it.
What are the types of dependency injection?
The main types are constructor injection, setter injection, and field injection. Constructor injection is generally preferred for required dependencies.
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