Dependency Injection · interview question
Why might you prefer constructor injection over field injection when unit testing?
Multiple choiceMediumchapter-9-curatedpremiumdependency-injectionconstructor-vs-field-injection
Answer and explanation
Correct answer
D. Constructor injection allows easier mocking of dependencies.
Why
Constructor injection allows you to easily pass mock objects as dependencies during testing, without needing to rely on reflection or other means to inject dependencies into private fields.
Test yourself on Dependency Injection
A free test with instant, explained results. No account needed.
More Dependency Injection questions
- What advantage does constructor injection offer over field injection concerning encapsulation?
- In Spring Boot, how does lazy initialization of beans affect constructor injection?
- How does Spring Boot handle dependency injection when multiple beans match the type being injected?
- Which scope of a bean in Spring Boot is the default in Java?
- Why do teams use the @Autowired annotation in Spring Boot in production code?
- Why is constructor injection preferred over field injection in terms of immutability?