Bird
0
0

Given the code below, what will be the output when app.run() 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 app.run() is called?
@Component
public class App {
  @Autowired
  private ServiceA serviceA;

  public void run() {
    System.out.println(serviceA.getName());
  }
}

@Component
public class ServiceA {
  public String getName() {
    return "ServiceA";
  }
}
ARuntime NullPointerException
Bnull
CServiceA
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand component scanning and injection

    Both App and ServiceA are annotated with @Component, so Spring creates and manages their instances. The @Autowired injects ServiceA into App.
  2. Step 2: Trace the method call

    Calling app.run() prints the result of serviceA.getName(), which returns "ServiceA".
  3. Final Answer:

    ServiceA -> Option C
  4. Quick Check:

    Autowired injects component = output string [OK]
Quick Trick: If both classes are @Component, autowired works and prints value [OK]
Common Mistakes:
  • Assuming serviceA is null without injection
  • Confusing compilation vs runtime errors
  • Forgetting to annotate both classes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes