Bird
0
0

Given the code below, what will be printed when useService() is called?

medium📝 component behavior Q13 of 15
Spring Boot - Inversion of Control and Dependency Injection
Given the code below, what will be printed when useService() is called?
@Component("serviceA")
class ServiceA implements Service { public String getName() { return "A"; } }
@Component("serviceB")
class ServiceB implements Service { public String getName() { return "B"; } }

@Autowired
@Qualifier("serviceB")
private Service service;

public void useService() {
  System.out.println(service.getName());
}
AB
BA
CserviceB
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Identify injected bean by @Qualifier

    @Qualifier("serviceB") tells Spring to inject the bean named "serviceB", which is ServiceB.
  2. Step 2: Check method output

    ServiceB's getName() returns "B", so printing service.getName() outputs "B".
  3. Final Answer:

    B -> Option A
  4. Quick Check:

    @Qualifier("serviceB") injects ServiceB = prints B [OK]
Quick Trick: Qualifier name matches bean name to pick correct implementation [OK]
Common Mistakes:
  • Assuming default bean is injected without @Qualifier
  • Confusing bean name with class name
  • Expecting compilation error due to multiple beans

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes