Bird
0
0

Why does the following code cause a NullPointerException at runtime?

medium📝 Debug Q7 of 15
Spring Boot - Inversion of Control and Dependency Injection
Why does the following code cause a NullPointerException at runtime?

@Component
public class OrderService {
  private PaymentService paymentService;

  public void process() {
    paymentService.pay();
  }
}
ApaymentService is not injected because @Autowired is missing
BPaymentService class is not annotated with @Component
Cprocess() method is private
DOrderService is missing a constructor
Step-by-Step Solution
Solution:
  1. Step 1: Check injection of paymentService

    Without @Autowired, Spring does not inject PaymentService, so paymentService remains null.
  2. Step 2: Understand NullPointerException cause

    Calling pay() on null causes NullPointerException.
  3. Final Answer:

    paymentService is not injected because @Autowired is missing -> Option A
  4. Quick Check:

    Missing @Autowired = null dependency = NullPointerException [OK]
Quick Trick: Always add @Autowired to inject dependencies [OK]
Common Mistakes:
  • Assuming Spring injects without @Autowired
  • Confusing method visibility with injection
  • Thinking constructor is mandatory for injection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes