Easy java spring

Constructor injection, setter injection or field injection: which do you use and why?

The 30 second answer

I use constructor injection for required dependencies, and that is what the Spring docs recommend. The fields can be final, the object can never exist half-built, and in a unit test I just call the constructor with mocks. Setter injection is for optional dependencies. Field injection with @Autowired on a private field hides dependencies, can't be final, and needs reflection or a Spring context to test, so I avoid it. With one constructor, Spring uses it without @Autowired.

<!-- level: 1 --> <!-- must_know: true -->

StyleHowWhen
ConstructorDependencies are constructor parametersRequired dependencies (the default choice)
Setter@Autowired on a setterOptional dependencies, or ones that may change
Field@Autowired on a private fieldAvoid in production code

The Spring Framework reference says that since you can mix the two, it is a good rule of thumb to "use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies". It also notes that constructor injection lets you build immutable objects and makes sure required dependencies are not null.

Practical reasons interviewers want to hear:

  • Immutability: fields can be final.
  • No half-built objects: the object can't exist without its dependencies.
  • Easy unit tests: new OrderService(fakePayments), no Spring context needed.
  • Design signal: a constructor with eight parameters shows the class does too much; field injection hides that.
  • If a class has only one constructor, Spring uses it automatically and @Autowired is not needed.
Sources (1)
  1. Spring Framework: Dependency injection (constructor-based or setter-based DI)docs.spring.io