Bird
0
0

Given the code below, what will be printed when myService.printMessage() is called?

medium📝 component behavior Q4 of 15
Spring Boot - Inversion of Control and Dependency Injection
Given the code below, what will be printed when myService.printMessage() is called?

@Component
public class MyService {
  @Autowired
  private MessageProvider provider;

  public void printMessage() {
    System.out.println(provider.getMessage());
  }
}

@Component
public class MessageProvider {
  public String getMessage() { return "Hello Spring"; }
}
Anull
BRuntime NullPointerException
CCompilation error
DHello Spring
Step-by-Step Solution
Solution:
  1. Step 1: Understand @Autowired effect on private field

    Spring injects the MessageProvider bean into the provider field automatically.
  2. Step 2: Trace the printMessage method

    Calling getMessage() on the injected provider returns "Hello Spring", which is printed.
  3. Final Answer:

    Hello Spring -> Option D
  4. Quick Check:

    Autowired injects bean, so output = Hello Spring [OK]
Quick Trick: Autowired injects bean, so method prints its return value [OK]
Common Mistakes:
  • Assuming provider is null without injection
  • Expecting compilation error due to private field
  • Confusing runtime errors with injection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes