Bird
0
0

Given the code below, what will be the output when the printMessage method is called?

medium📝 component behavior Q13 of 15
Spring Boot - Inversion of Control and Dependency Injection
Given the code below, what will be the output when the printMessage method is called?
\@Component
public class Printer {
  private final MessageService service;
  public Printer(MessageService service) {
    this.service = service;
  }
  public void printMessage() {
    System.out.println(service.getMessage());
  }
}

\@Component
public class MessageService {
  public String getMessage() {
    return "Hello Spring!";
  }
}
Anull
BHello Spring!
CCompilation error
DRuntime NullPointerException
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor injection wiring

    Spring injects MessageService into Printer via constructor, so service is not null.
  2. Step 2: Check method output

    Calling service.getMessage() returns "Hello Spring!", which is printed.
  3. Final Answer:

    Hello Spring! -> Option B
  4. Quick Check:

    Injected service returns message [OK]
Quick Trick: Constructor injection ensures dependencies are not null [OK]
Common Mistakes:
  • Assuming service is null without injection
  • Confusing field injection with constructor injection
  • Expecting compilation error due to missing annotations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes