Spring / Spring7 Intermediate to Advanced Interview questions
Why should you avoid field injection in production Spring codebases?
Field injection hides a class's real dependencies from anyone reading its public API - the constructor signature says nothing about what the class actually needs, so understanding its requirements means scanning every field for @Autowired annotations instead of reading one method signature.
// field injection - hidden dependency, can't be final @Autowired private PaymentGateway gateway; // constructor injection - explicit, can be final private final PaymentGateway gateway; public OrderService(PaymentGateway gateway) { this.gateway = gateway; }
It also blocks marking the field final, so nothing in the language stops a dependency from being reassigned later, and it means the class can't be instantiated at all outside a DI container without resorting to reflection tricks like ReflectionTestUtils.setField in tests - true, container-free unit tests with plain new and hand-wired mocks become impossible. Finally, field injection delays failure: since injection happens after the constructor runs, a missing or misconfigured dependency surfaces as a NullPointerException later, whenever the field is first used, rather than immediately and clearly at object-construction time the way a missing constructor argument would.
More Related questions...