Constructor injection is the preferred dependency injection approach in Spring because it ensures that all required dependencies are provided when an object is created. This results in more reliable, immutable, and testable classes while preventing partially initialized objects.
Key Points: • Constructor injection guarantees that mandatory dependencies are available during object creation. • It promotes immutability because dependencies can be declared as final and cannot be changed later. • It improves testability by making dependencies explicit and easy to provide during unit testing.
Example: Consider an OrderService that requires a PaymentService to function. With constructor injection, the OrderService cannot be created unless a valid PaymentService is provided, ensuring the object is always in a valid state.
Code Example:
@Service
public class OrderService {
private final PaymentService paymentService;
public OrderService(
PaymentService paymentService) {
this.paymentService =
paymentService;
}
public void placeOrder() {
paymentService.processPayment();
}
}Setter Injection Example:
@Service
public class OrderService {
private PaymentService paymentService;
@Autowired
public void setPaymentService(
PaymentService paymentService) {
this.paymentService =
paymentService;
}
}Issue: • The object can be created without setting the dependency. • This may lead to NullPointerException if the dependency is not injected.
Advantages of Constructor Injection: • Prevents incomplete object creation. • Supports immutable design using final fields. • Makes dependencies clearly visible. • Simplifies unit testing without Spring. • Encourages proper design by exposing excessive dependencies.
When to Use Setter Injection: • Optional dependencies. • Dependencies that may change after object creation. • Legacy applications requiring flexible configuration.
Interview Tip: A concise interview answer is: Constructor injection is recommended because it guarantees that all required dependencies are available at object creation time, prevents partially initialized objects, supports immutability through final fields, and improves testability. Setter injection is generally reserved for optional or configurable dependencies.