Constructor injection vs. setter injection in Spring Boot
The Spring Framework allows developers to inject dependencies into their applications in one of three different ways:
- Field injection.
- Setter injection.
- Constructor injection.
Developers typically use field injection only on small projects and prototypes, due to its inability to support immutable variables and the incompatibilities it creates with many testing frameworks.
Constructor injection vs. setter injection
That leaves software architects and Spring developers wondering which dependency injection approach their inversion of control container should take: setter or constructor?
Here's the short answer: Always use constructor injection in your Spring and Spring Boot applications unless a seriously compelling reason forces your hand and setter injection is a must.
The longer answer? Watch this video on the difference between setter and constructor injection in Spring.
Cameron McKenzie has been a Java EE software engineer for 20 years. His current specialties include Agile development; DevOps; Spring; and container-based technologies such as Docker, Swarm and Kubernetes.