Video in progress
Why is constructor injection better than field injection in Spring?
With constructor injection the dependencies are final, the object is never created half-ready, and in tests you can create it with new without Spring. Field injection hides the dependencies and makes it invisible that a class depends on too many things.
📖 Answer
// field injection
@Service
class InvoiceService {
@Autowired private InvoiceRepository repo;
@Autowired private MailSender mail;
}
// constructor injection
@Service
class InvoiceService {
private final InvoiceRepository repo;
private final MailSender mail;
InvoiceService(InvoiceRepository repo, MailSender mail) {
this.repo = repo;
this.mail = mail;
}
}
With a single constructor, @Autowired hasn't been required since Spring 4.3.
The differences in practice:
- Testing. With field injection, if you do
new InvoiceService(), the fields arenull, so you need reflection or the Spring context. With a constructor, you just writenew InvoiceService(fakeRepo, fakeMail). - Immutability.
finalfields mean the dependency can't be swapped after the bean is created. - A design signal. 8 parameters in a constructor are plainly visible and raise the question "this class is doing too much". With field injection, 8
@Autowiredlines go unnoticed. - Circular dependencies. With constructor injection they fail right at startup; since Spring Boot 2.6, circular dependencies are prohibited by default.
Field injection looks normal only in test classes (@Autowired MockMvc).
Sign up to mark studied questions and save your progress.