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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
