Bird
0
0

How do you correctly perform constructor-based dependency injection in a Spring Boot component?

easy📝 Syntax Q3 of 15
Spring Boot - Inversion of Control and Dependency Injection
How do you correctly perform constructor-based dependency injection in a Spring Boot component?
ACreate a setter method annotated with @Bean
BUse @Autowired on a private field without a constructor
CDeclare a constructor with the dependency as a parameter and annotate the class with @Component
DDeclare dependencies as static variables
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor injection

    Constructor injection requires a constructor with dependencies as parameters.
  2. Step 2: Recognize correct usage

    Annotate the class with @Component so Spring manages it.
  3. Step 3: Exclude incorrect options

    @Autowired on fields is field injection, @Bean is for factory methods, static variables are not injected.
  4. Final Answer:

    Declare a constructor with the dependency as a parameter and annotate the class with @Component -> Option C
  5. Quick Check:

    Constructor injection uses constructor parameters [OK]
Quick Trick: Constructor injection uses constructor parameters [OK]
Common Mistakes:
  • Confusing field injection with constructor injection
  • Using @Bean on setters instead of @Autowired

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes