Bird
0
0

Given this Spring Boot code snippet, what will be printed when the application runs?

medium📝 component behavior Q4 of 15
Spring Boot - Inversion of Control and Dependency Injection
Given this Spring Boot code snippet, what will be printed when the application runs?
 @Component class A { public A() { System.out.println("A created"); } }
@Component class B { public B(A a) { System.out.println("B created with " + a); } }
AOnly A created
BA created\nB created with A@<hashcode>
CB created with null\nA created
DCompilation error due to missing annotations
Step-by-Step Solution
Solution:
  1. Step 1: Understand bean creation order

    Spring creates bean A first, printing "A created". Then it creates B, injecting A, printing "B created with A@".
  2. Step 2: Eliminate wrong outputs

    B created with null\nA created is wrong because B cannot get null for A. Only A created misses B creation. Compilation error due to missing annotations is wrong; annotations are correct.
  3. Final Answer:

    A created\nB created with A@<hashcode> -> Option B
  4. Quick Check:

    Bean creation order = A then B with injected A [OK]
Quick Trick: Beans are created in dependency order, dependencies injected automatically [OK]
Common Mistakes:
  • Assuming dependencies are null during injection
  • Thinking beans are created in random order
  • Missing that constructor runs on bean creation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes