Dependency Injection · interview question
Why can using field injection with private fields in a Spring Boot application become a problem in practice?
Multiple choiceEasychapter-9-curatedpremiumdependency-injectionconstructor-vs-field-injection
Answer and explanation
Correct answer
A. Makes the class difficult to unit test
Why
Field injection with private fields makes the class difficult to unit test because dependencies cannot be easily mocked or swapped. Constructor injection facilitates testability by allowing dependencies to be injected at the time of object creation.
Test yourself on Dependency Injection
A free test with instant, explained results. No account needed.
More Dependency Injection questions
- In Spring Boot, how can you ensure that a bean is eagerly initialized at startup?
- 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?