Bird
0
0

Which of the following is the correct way to inject a dependency using constructor injection in Spring Boot?

easy📝 Syntax Q12 of 15
Spring Boot - Inversion of Control and Dependency Injection
Which of the following is the correct way to inject a dependency using constructor injection in Spring Boot?
A@Autowired private Service service;
BService service = new Service();
Cpublic MyClass(Service service) { this.service = service; }
D@Autowired public void setService(Service service) { this.service = service; }
Step-by-Step Solution
Solution:
  1. Step 1: Identify constructor injection syntax

    Constructor injection requires a constructor that accepts the dependency as a parameter and assigns it to a field.
  2. Step 2: Match the correct code

    public MyClass(Service service) { this.service = service; } shows a constructor receiving Service and assigning it, which is the correct pattern.
  3. Final Answer:

    public MyClass(Service service) { this.service = service; } -> Option C
  4. Quick Check:

    Constructor injection = constructor with parameters [OK]
Quick Trick: Constructor injection uses constructor parameters, not field annotations [OK]
Common Mistakes:
  • Confusing field injection with constructor injection
  • Using manual object creation instead of injection
  • Using setter injection when constructor injection is asked

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes