Bird
0
0

Why is constructor injection with @Autowired generally preferred over field injection in Spring Boot?

hard📝 Conceptual Q10 of 15
Spring Boot - Inversion of Control and Dependency Injection
Why is constructor injection with @Autowired generally preferred over field injection in Spring Boot?
AField injection requires public fields which is unsafe
BConstructor injection makes dependencies explicit and supports immutability
CConstructor injection is faster at runtime
DField injection does not work with @Component classes
Step-by-Step Solution
Solution:
  1. Step 1: Compare constructor and field injection

    Constructor injection requires dependencies to be passed in, making them clear and allowing final fields.
  2. Step 2: Benefits of constructor injection

    This approach supports immutability and easier testing, improving code quality.
  3. Final Answer:

    Constructor injection makes dependencies explicit and supports immutability -> Option B
  4. Quick Check:

    Constructor injection = explicit dependencies + immutability [OK]
Quick Trick: Constructor injection clarifies dependencies and allows final fields [OK]
Common Mistakes:
  • Thinking field injection requires public fields
  • Assuming constructor injection is about speed
  • Believing field injection doesn't work with components

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes