Sub topic 5
Constructor, setter and field injection
This chapter assumes you know what a bean is, how the ApplicationContext creates beans, and basic Java annotations. It covers the three ways Spring can hand a dependency to a bean, and which one to choose.
The three injection styles
Spring can supply a dependency through a constructor parameter, a setter method, or directly into a field. All three use the same resolution rules, which a later chapter covers. They differ in when the dependency arrives and what the class promises about it.
Constructor injection
The class declares its dependencies as constructor parameters. Spring calls the constructor with matching beans.
@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 the object is fully built and immutable once the constructor returns. If a required bean is missing, the context fails at startup instead of failing later with a NullPointerException.
If a class has several constructors, mark the one Spring should use with @Autowired. Otherwise Spring looks for a no-argument constructor.
Setter injection
Spring creates the object first, then calls annotated setters.
@Service
public class ReportService {
private Formatter formatter = new PlainFormatter();
@Autowired(required = false)
public void setFormatter(Formatter formatter) {
this.formatter = formatter;
}
}This style fits optional dependencies that have a sensible default. With required = false, Spring skips the call when no Formatter bean exists, and the default stays in place. The cost is that the object can exist in a half-configured state, and the field cannot be final.
Field injection
Spring sets the field itself, using reflection.
@Service
public class AuditService {
@Autowired
private MessageSender sender;
}This is the shortest form, but it hides the dependency. The constructor says nothing about what the class needs. The field cannot be final. Outside Spring, a test has no constructor or setter to call, so it needs reflection or a container to set the field.
Comparing the styles
| Aspect | Constructor | Setter | Field |
|---|---|---|---|
| Dependencies visible in the API | Yes | Partly | No |
| Can use `final` fields | Yes | No | No |
| Handles optional dependencies | Awkward | Good | Possible |
| Easy to test without Spring | Yes | Yes | No |
| Detects circular references early | Yes | No | No |
Choosing a style
Use constructor injection by default. It makes required dependencies explicit and keeps objects immutable. A constructor with many parameters is also a visible warning that the class does too much.
Use setter injection for dependencies that are truly optional or that may be replaced after construction. Avoid field injection in application code. It is mainly seen in older code, and in test classes where the framework requires it.
Common errors
NoSuchBeanDefinitionExceptionorUnsatisfiedDependencyExceptionat startup means no bean matches the parameter type. Check that the class is scanned or declared with@Bean.NoUniqueBeanDefinitionExceptionmeans several beans match. Resolve it with@Primaryor@Qualifier.- A
NullPointerExceptionon a field-injected dependency usually means you created the object withnew. Spring only injects objects it manages. - A
BeanCurrentlyInCreationExceptionpoints to a circular dependency, which constructor injection exposes at startup.
Constructor injection and testing
Because the dependency is a plain constructor argument, a test can pass a fake directly.
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!"
}
}No container starts, so the test runs in milliseconds.
Exercise
A teammate writes a service with @Autowired private OrderRepository repo; and a unit test that calls new OrderService(). The test fails with a NullPointerException when the service uses repo. Why does it fail, and how would you change the class?
Show answer
Spring injects the field only into beans it creates. The test builds the object with new, so no injection happens and repo stays null. Change the class to take OrderRepository as a constructor parameter and store it in a final field. The test can then call new OrderService(fakeRepo), and Spring still injects the bean at runtime.