Real-World Analogy for Beginners
Think of a Gaming Console. You buy the console first. Adding an extra wireless controller or steering wheel later is optional. You use the setController() method to plug it in when available. If not plugged in, the console still turns on!
What is Setter Injection?
Setter Injection means passing a dependency into a class using a setter method (e.g. setAuditLogger(...)) annotated with @Autowired.
When Should You Use Setter Injection?
Use Setter Injection only when the dependency is optional or needs to be swapped/reconfigured while the application is running.
NotificationService.java
@Service
public class NotificationService {
private SmsGateway smsGateway;
// Optional dependency: required = false prevents Spring from throwing error if SmsGateway bean is missing
@Autowired(required = false)
public void setSmsGateway(SmsGateway smsGateway) {
this.smsGateway = smsGateway;
}
public void notifyUser(String message) {
if (smsGateway != null) {
smsGateway.sendSms(message);
} else {
System.out.println("SMS Gateway not configured. Message skipped.");
}
}
}