Spring Boot core · Trade-off
Constructor or field injection
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- How do you unit test a class that uses field injection?
- With Lombok, how do you get constructor injection with little code?
- When is setter injection the right choice?
- The constructor now takes nine dependencies. What does that tell you?
- 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 callnew 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
@RequiredArgsConstructorwithprivate finalfields 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.
@Lazyhides 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 voicePractise 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.