Bird
0
0

You have a Spring Boot service class that uses field injection:

hard📝 Application Q15 of 15
Spring Boot - Inversion of Control and Dependency Injection
You have a Spring Boot service class that uses field injection:
public class OrderService {
  @Autowired
  private PaymentService paymentService;

  public boolean processOrder(Order order) {
    return paymentService.charge(order.getAmount());
  }
}

How would switching to constructor injection improve this class?
AIt makes dependencies explicit and improves testability
BIt removes the need to annotate fields with <code>@Autowired</code>
CIt automatically creates new instances of dependencies
DIt allows Spring to inject dependencies without a constructor
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor injection benefits

    Constructor injection requires dependencies to be passed in explicitly, making them visible and clear in the class design.
  2. Step 2: Analyze testability improvements

    Explicit dependencies allow easy replacement with mocks or stubs during testing, improving testability and code clarity.
  3. Final Answer:

    It makes dependencies explicit and improves testability -> Option A
  4. Quick Check:

    Constructor injection = explicit dependencies + better tests [OK]
Quick Trick: Constructor injection shows dependencies clearly, aiding tests [OK]
Common Mistakes:
  • Thinking constructor injection removes @Autowired completely
  • Believing constructor injection creates new instances automatically
  • Assuming Spring injects without constructor or annotations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes