Bird
0
0

Consider a Spring Boot service with a constructor that injects a dependency and also performs logic inside the constructor. Why is this discouraged?

hard📝 Application Q9 of 15
Spring Boot - Inversion of Control and Dependency Injection
Consider a Spring Boot service with a constructor that injects a dependency and also performs logic inside the constructor. Why is this discouraged?
AConstructor should only assign dependencies, not execute business logic
BSpring requires constructors to be empty
CLogic in constructor causes beans to be created twice
DIt prevents Spring from injecting dependencies
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor responsibility

    Constructor injection should only assign dependencies to fields.
  2. Step 2: Identify issues with logic in constructor

    Executing business logic in constructor can cause side effects before bean is fully initialized.
  3. Final Answer:

    Constructor should only assign dependencies, not execute business logic -> Option A
  4. Quick Check:

    Keep constructors clean for safe dependency injection [OK]
Quick Trick: Avoid business logic inside constructors [OK]
Common Mistakes:
  • Thinking Spring requires empty constructors
  • Believing logic in constructor triggers double creation
  • Assuming logic blocks injection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes