Constructor Injection and Setter Injection are two techniques used in Spring to provide dependencies to a bean. Constructor Injection supplies dependencies at the time of object creation, while Setter Injection provides them after the object has been created.
Key Points: • Constructor Injection ensures that all required dependencies are available when the object is instantiated. • Setter Injection is typically used for optional dependencies that may change after object creation. • Constructor Injection promotes immutability because dependencies can be declared as final. • Setter Injection allows dependencies to be modified or reconfigured later. • Constructor Injection is generally preferred in modern Spring applications because it improves testability and prevents partially initialized objects.
Example: A UserService class that cannot function without a UserRepository should use Constructor Injection. A NotificationService that is optional can be injected using Setter Injection.
Code Example:
// Constructor Injection
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
// Setter Injection
@Service
public class NotificationService {
private EmailService emailService;
@Autowired
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
}Interview Tip: A concise interview answer is:
"Constructor Injection is used for mandatory dependencies and ensures that an object is fully initialized at creation time. Setter Injection is suitable for optional dependencies that may need to be changed later. Constructor Injection is generally recommended because it improves immutability, testability, and reliability."
Quick Comparison:
Constructor Injection: • Mandatory dependencies • Supports immutability • Preferred approach
Setter Injection: • Optional dependencies • Allows dependency modification • More flexible but less strict