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 are null, so you need reflection or the Spring context. With a constructor, you just write new InvoiceService(fakeRepo, fakeMail).
  • Immutability. final fields 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 @Autowired lines 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).