Sub topic 5
Constructor, setter and field injection
Earlier chapters covered what dependency injection (DI) is and what a bean is. This chapter covers the three ways Spring can hand a dependency to a bean, and how to choose between them. It assumes you know Java classes, interfaces, constructors and annotations. It also assumes you have seen @Service and @Autowired before.
The three injection styles
A bean needs collaborators. Spring can supply them in three places: through the constructor, through a setter method, or directly into a field. All three are driven by the same container. They differ in when the dependency arrives and in what guarantees the class gets.
Constructor injection
The class lists its dependencies as constructor parameters. Spring resolves each parameter from the container, then calls the constructor.
public interface MessageSender {
void send(String to, String body);
}
@Service
public class NotificationService {
private final MessageSender sender;
// With a single constructor, @Autowired is optional.
public NotificationService(MessageSender sender) {
this.sender = sender;
}
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}The field is final, so it is assigned exactly once. No code can create a NotificationService without a sender. Since Spring 4.3, a class with exactly one constructor does not need @Autowired on it.
Setter injection
The class has a no-argument constructor (or a constructor for its required dependencies) and exposes setters. Spring creates the object first, then calls the annotated setters.
interface AuditLog {
void record(String event);
}
@Service
public class ReportService {
private final MessageSender sender;
private AuditLog auditLog; // optional collaborator
public ReportService(MessageSender sender) {
this.sender = sender;
}
@Autowired(required = false)
public void setAuditLog(AuditLog auditLog) {
this.auditLog = auditLog;
}
public void publish(String user) {
sender.send(user, "Report ready");
if (auditLog != null) {
auditLog.record("report:" + user);
}
}
}Here MessageSender is required, so it comes through the constructor. AuditLog is optional. If no AuditLog bean exists, Spring skips the setter and the field stays null. The null check is the price of that flexibility.
Field injection
The dependency is declared as a field with @Autowired. Spring sets it by reflection after instantiation.
@Service
public class LegacyNotificationService {
@Autowired
private MessageSender sender;
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}This is the shortest form, and you will see it in a lot of older code and tutorials. It also has the most problems, covered below.
What happens when
The styles differ in timing. Constructor arguments must exist before the object does. Setters and fields are filled in after the object exists.
The consequence is simple. Inside a constructor, field-injected and setter-injected dependencies are still null. Constructor-injected ones are already there. A constructor that calls sender.send(...) works only if sender arrived as a constructor parameter.
Comparing the styles
| Property | Constructor | Setter | Field |
|---|---|---|---|
| Dependency can be `final` | Yes | No | No |
| Object is complete once built | Yes | No, until setters run | No |
| Good for optional dependencies | Awkward | Yes | Possible |
| Dependencies visible in the class signature | Yes | Partly | No |
| Usable without Spring (plain `new`) | Yes | Yes | Not without reflection |
| Can resolve circular references | No | Sometimes | Sometimes |
Why constructor injection is the default choice
Spring's own documentation recommends constructor injection for mandatory dependencies. The reasons are practical.
- Required means required. If a bean is missing, the context fails at startup with a clear error. It does not fail later with a
NullPointerExceptionin a request. - Immutability.
finalfields give you safe publication across threads. Singleton beans are shared by many threads, so this matters. - Honest design. A constructor with seven parameters is visibly a class with too many responsibilities. Field injection hides the same problem, because adding a tenth
@Autowiredfield costs one line. - Testability. You can build the object with
newand pass a fake, with no container and no reflection. See the test below. - Cycle detection. Two beans that need each other through constructors cannot be built at all, and Spring reports it immediately. That is usually a design error you want to know about.
import java.util.ArrayList;
import java.util.List;
class NotificationServiceTest {
void welcomeSendsMessage() {
List<String> sent = new ArrayList<>();
NotificationService service =
new NotificationService((to, body) -> sent.add(to + ":" + body));
service.welcome("ana");
// sent now contains "ana:Welcome!"
}
}MessageSender has one method, so a lambda works as a fake. Nothing here starts Spring.
Problems with field injection
Field injection looks convenient but costs you several things.
- No
final. The field is assigned after construction, so it must be mutable. - Silent
nulloutside the container.new LegacyNotificationService().welcome("ana")throwsNullPointerException, and nothing in the class signature warns you. - Tests need machinery. You need Spring's
ReflectionTestUtils.setField, Mockito's@InjectMocks, or a Spring test context just to put a fake in place. - Hidden dependency growth. There is no constructor to grow awkward, so classes accumulate collaborators unnoticed.
- Tight coupling to the container. The class cannot be used correctly without a DI framework, which defeats part of the purpose of DI.
Field injection is still acceptable in two places. One is test classes, where @Autowired fields in a Spring test are common and the class is never instantiated by hand. The other is quick throwaway code.
When setter injection is the right tool
Use a setter when the dependency is genuinely optional, or when it has a sensible default that callers may replace. The ReportService example shows the first case. Setters also let a bean be reconfigured after creation, which is rare in modern Spring applications.
You have other ways to express optionality that avoid a mutable field:
- A constructor parameter of type
Optional<AuditLog>. - A constructor parameter of type
ObjectProvider<AuditLog>, which also lets you fetch lazily withgetIfAvailable(). - A constructor parameter annotated with
@Nullable.
@Service
public class ReportServiceV2 {
private final MessageSender sender;
private final Optional<AuditLog> auditLog;
public ReportServiceV2(MessageSender sender, Optional<AuditLog> auditLog) {
this.sender = sender;
this.auditLog = auditLog;
}
public void publish(String user) {
sender.send(user, "Report ready");
auditLog.ifPresent(log -> log.record("report:" + user));
}
}This keeps both fields final and makes the optional dependency explicit in the type. The class needs import java.util.Optional;.
Edge cases and common errors
More than one constructor
If a class has several constructors, Spring does not guess. Mark the one it should use with @Autowired. Without that mark, Spring falls back to the no-argument constructor. If there is none, it fails with a message that no default constructor was found.
@Service
public class AlertDispatcher {
private final MessageSender sender;
public AlertDispatcher() {
this(null);
}
@Autowired
public AlertDispatcher(MessageSender sender) {
this.sender = sender;
}
}Only one constructor may be marked with @Autowired (with the default required = true).
Missing dependency
If no bean of the required type exists, the context fails at startup with NoSuchBeanDefinitionException (reported as UnsatisfiedDependencyException during wiring). This happens for all three styles unless the injection point is optional. The usual causes are a missing @Component or @Service, or a class outside the scanned packages.
Circular references
Say A needs B through its constructor and B needs A through its constructor. Spring cannot build either, and it reports BeanCurrentlyInCreationException. Setter and field injection can sometimes break such a cycle, because the objects exist before they are wired. Spring Boot 2.6 and later forbid circular references by default for this reason. Treat a cycle as a design flaw and restructure the classes. A later chapter covers diagnosing it.
Too many parameters
A long constructor parameter list is a signal, not an injection problem. Splitting the class into smaller ones fixes it. Switching to field injection to hide the list does not.
Choosing a style
In short, use constructor injection by default, setters for optional or replaceable collaborators, and reserve field injection for test classes.
Exercise
A class has @Autowired private AuditLog auditLog; and a method that calls auditLog.record(...). A teammate writes new MyService().run() in a unit test and gets a NullPointerException. Why does this happen, and how would you change the class so the test works without Spring?
Show answer
Field injection is performed by the container through reflection after it instantiates the bean. When the test calls new directly, no container is involved, so the field stays null. Change the class to take AuditLog as a final field set in the constructor. The test can then call new MyService(fakeAuditLog).run() with a simple fake or lambda.
Exercise
A service needs a MessageSender to function and may use an AuditLog if one is defined. Describe how you would declare both dependencies so that the context fails at startup when MessageSender is missing but starts normally when AuditLog is missing.
Show answer
Take MessageSender as a plain constructor parameter, which makes it required and fails startup if no bean exists. Declare the optional dependency either as an Optional<AuditLog> or ObjectProvider<AuditLog> constructor parameter, or as a setter annotated @Autowired(required = false). The first option keeps both fields final.