Bird
0
0

Examine the following Spring component:

medium📝 Debug Q6 of 15
Spring Boot - Inversion of Control and Dependency Injection
Examine the following Spring component:
@Component
public class Processor {
  @Autowired
  private Helper helper;

  public Processor() {
    System.out.println(helper.process());
  }
}

What is the issue with this code?
AThe constructor should be annotated with <code>@Autowired</code>.
BThe <code>@Component</code> annotation is missing on the Helper class.
CThe <code>helper</code> field is not injected before the constructor runs, causing a NullPointerException.
DThe <code>process()</code> method must be static.
Step-by-Step Solution
Solution:
  1. Step 1: Understand injection timing

    Field injection happens after the constructor completes.
  2. Step 2: Constructor uses uninitialized field

    Calling helper.process() in the constructor causes NullPointerException because helper is null.
  3. Step 3: Correct approach

    Use constructor injection or avoid using injected fields in constructor.
  4. Final Answer:

    The helper field is not injected before the constructor runs, causing a NullPointerException. -> Option C
  5. Quick Check:

    Are fields injected before constructor execution? No [OK]
Quick Trick: Field injection happens after constructor runs [OK]
Common Mistakes:
  • Assuming @Autowired fields are ready in constructor
  • Thinking constructor must be @Autowired
  • Believing process() must be static

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes