When to Use Setter Injection in Spring
Fast recall
Quick revision
Core answer
Whether you can name a genuine use for setter injection rather than dismissing it after hearing 'use constructor injection'.
Saying setter injection is never useful, or using it for required dependencies and getting a null at runtime.
Give a real optional-dependency example and show the null-safety guard the pattern requires.
Interview-ready guide
Interview answer
A class should leave its constructor in a usable state. That makes constructor injection the default for repositories, gateways, and other required collaborators. Setter injection can fit an optional audit sink or plug-in where the class has a defined no-op behavior when no bean exists. @Autowired(required=false) on a method is one mechanism, but Optional or ObjectProvider often states the choice more clearly. A setter also makes reassignment possible, so use it only when that mutability is intended rather than as a workaround for a dependency cycle.
For example, OrderService should receive its required OrderRepository in the constructor, but an optional AuditPublisher may be supplied through a setter when the service has a safe behavior without it.
When to Use Setter Injection in Spring
Direct Answer
Setter injection is useful for a dependency that is genuinely optional or reconfigurable after construction. Keep required collaborators in the constructor. If a Spring bean may be absent, model that deliberately with Optional, ObjectProvider, or a non-required injection method and define behavior for the absent case; do not let an unexplained null become a later failure.
Code Example
@Service
class NotificationService {
private SmsSender smsSender; // optional, can stay null
// Optional dependency wired via a setter after construction
@Autowired(required = false)
public void setSmsSender(SmsSender smsSender) {
this.smsSender = smsSender;
}
void notifyUser(String msg) {
if (smsSender != null) { // guard the null before use
smsSender.send(msg);
}
}
}
Common Mistakes & Pitfalls
- Overusing setter injection: Freshers mark everything optional to avoid constructor complexity, which hides true dependencies. If a dependency is required for core logic, force it through the constructor.
- Forgetting null checks: Marking a setter required=false but then calling methods on the field without a null check leads to a NullPointerException where the bean isn't configured.
- Using setter injection for testability: Some use setters so they can swap dependencies after construction. That's an anti-pattern — use constructor injection and pass mocks in tests instead.
Check your understanding
Answer these without looking back at the article.
- How do you declare an optional dependency in Spring?
- What is @Autowired(required=false)?
- How do you use Optional<T> for optional dependency injection?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.