What is dependency injection and why prefer constructor injection in Spring Boot?
Quick Summary: Dependency Injection (DI) is a design pattern where the Spring IoC container creates and passes required collaborating beans into an object rather than letting the object instantiate them itself; constructor injection guarantees immutability, required invariants, and clean unit testing.
Direct Interview Answer
In Spring Boot, the IoC Container (ApplicationContext) manages bean instantiation, configuration, and wiring. Instead of tightly coupling OrderService to new RazorpayGateway(), dependencies are injected via interfaces.
Constructor injection is strongly recommended over field @Autowired because dependencies can be marked private final, missing required beans fail loudly at startup, and plain JUnit tests can instantiate services using new without booting a Spring context.
Detailed Technical Explanation
When a bean has a single constructor in Spring 4.3+, @Autowired is optional—Spring automatically uses that constructor. Field injection hides tight dependency explosion (10+ injected fields signal an SRP violation) and allows creating partially initialized objects in non-Spring tests leading to hidden NullPointerException failures.
Practical Walkthrough
Service wired via single constructor with interface abstraction.
@Service
public class EnrollmentService {
private final StudentRepository students;
private final PaymentGateway payments;
public EnrollmentService(StudentRepository students, PaymentGateway payments) {
this.students = students;
this.payments = payments;
}
public boolean enroll(String email, int amountInr) {
return payments.capture(email, amountInr) && students.markActive(email);
}
}
Immutable final dependencies wired at bean creation; easily mockable in plain JUnit 5.
Real-World Production Use Case
Decoupling payment providers, email dispatchers, and repositories across 15+ Spring Boot microservices so mock doubles can run unit tests in milliseconds.
Common Interview Mistakes to Avoid
- Using @Autowired directly on private fields, making unit testing awkward and hiding circular dependencies.
- Ignoring circular dependency cycles instead of refactoring shared domain logic or events.
- Forgetting @Qualifier when two implementations exist for one interface (causing NoUniqueBeanDefinitionException).