Skip to the page

Spring Boot core · Trade-off

Constructor or field injection

The interviewer asks

Half the code base uses @Autowired on fields, the other half uses constructors. A new joiner asks which one to use. What do you tell them, and why?

Then

Follow-ups the interviewer asks next

  1. How do you unit test a class that uses field injection?
  2. With Lombok, how do you get constructor injection with little code?
  3. When is setter injection the right choice?
  4. The constructor now takes nine dependencies. What does that tell you?
  5. What happens with a circular dependency when you use constructors?

The answer

What a strong answer covers

  • Constructor injection: dependencies can be final, the object is never half-built, and a plain unit test can call new OrderService(fakeRepo, fixedClock) with no Spring at all. With a single constructor, @Autowired isn't needed.
  • Field injection hides what the class needs, needs reflection or a Spring context to test, and leaves nulls when the class is built outside Spring.
  • Lombok's @RequiredArgsConstructor with private final fields is the common short form.
  • Setter injection only for optional dependencies or ones that can change after creation (rare).
  • Many constructor parameters is a design smell: the class does too much and should be split.
  • A circular dependency with constructors fails at startup, which is good: it shows a design problem. Fix it with a third bean that holds the shared logic, or with events. @Lazy hides the problem.

The red pen

Common traps

Avoid:"field injection is fine because it's shorter"; putting @Autowired everywhere; turning on allow-circular-references to make startup pass.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview