Bird
0
0

You want to create a service that depends on two other services managed by Spring IoC. How should you design the constructor to follow best practices?

hard📝 Conceptual Q8 of 15
Spring Boot - Inversion of Control and Dependency Injection
You want to create a service that depends on two other services managed by Spring IoC. How should you design the constructor to follow best practices?
ADeclare dependencies as public fields and assign them later
BUse constructor injection with both dependencies as parameters
CUse static methods to access dependencies
DManually instantiate dependencies inside the constructor
Step-by-Step Solution
Solution:
  1. Step 1: Understand dependency injection best practice

    Constructor injection is preferred for mandatory dependencies.
  2. Step 2: Design constructor with parameters for both dependencies

    Pass both dependencies as constructor parameters so Spring can inject them.
  3. Final Answer:

    Use constructor injection with both dependencies as parameters -> Option B
  4. Quick Check:

    Constructor injection for multiple dependencies = Best practice [OK]
Quick Trick: Inject all required dependencies via constructor parameters [OK]
Common Mistakes:
  • Instantiating dependencies manually inside constructor
  • Using static methods for dependencies
  • Exposing dependencies as public fields

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes