Spring Core · interview question
In a Spring Boot e-commerce application, why is constructor injection preferred over field injection for a @Service class?
Multiple choiceMediumchapter-9-curatedpremiumspring-corecontrollers-services-repositories
Answer and explanation
Correct answer
B. It allows for easier testing and immutability.
Why
Constructor injection is preferred because it promotes immutability and makes the class easier to test by explicitly requiring its dependencies. With constructor injection, the dependencies are required at instantiation, which helps catch errors early during application startup. Field injection, on the other hand, can result in hidden dependencies and make testing more challenging.
Test yourself on Spring Core
A free test with instant, explained results. No account needed.
More Spring Core questions
- In a Spring Boot application, what happens if a method annotated with @Transactional calls a private method also…
- Which layer should coordinate inventory checks, payment, and order persistence for a checkout request?
- What role do Entities typically play in a Spring Boot application?
- How can you externalize configuration in a Spring Boot application?
- Which issue might arise from using field injection in Spring Boot, particularly when managing dependencies?
- In a Spring Boot application, what is the main purpose of the @ComponentScan annotation?