2V0-72.22PSE · Question #68
Given an ApplicationContext containing three bean definitions of type Foo with bean ids foo1, foo2, and foo3, which three @Autowired scenarios are valid and will allow the ApplicationContext to…
The correct answer is B. @Autowired @Qualifier ("foo3") Foo foo; C. @Autowired public void setFoo (@Qualifier ("foo1") Foo foo) {...} E. @Autowired private Foo foo2. B, C, and E succeed because Spring resolves ambiguity among multiple same-type beans either through an explicit @Qualifier or by matching the field name to a bean ID: B uses @Qualifier("foo3") on the field, C uses @Qualifier("foo1") on the method parameter, and E relies on the…
Question
Given an ApplicationContext containing three bean definitions of type Foo with bean ids foo1, foo2, and foo3, which three @Autowired scenarios are valid and will allow the ApplicationContext to initialize successfully? (Choose three.)
Options
- A@Autowired public void setFoo (Foo foo) {...}
- B@Autowired @Qualifier ("foo3") Foo foo;
- C@Autowired public void setFoo (@Qualifier ("foo1") Foo foo) {...}
- D@Autowired private Foo foo;
- E@Autowired private Foo foo2;
- F@Autowired public void setFoo(Foo foo2) {...}
How the community answered
(28 responses)- A11% (3)
- B71% (20)
- D4% (1)
- F14% (4)
Explanation
B, C, and E succeed because Spring resolves ambiguity among multiple same-type beans either through an explicit @Qualifier or by matching the field name to a bean ID: B uses @Qualifier("foo3") on the field, C uses @Qualifier("foo1") on the method parameter, and E relies on the field name foo2 matching the bean ID foo2 as a fallback qualifier.
A and D both fail because the field/parameter name is foo, and no bean with that ID exists - Spring cannot choose among foo1, foo2, and foo3 and throws a NoUniqueBeanDefinitionException. F looks similar to E but fails because Spring does not reliably use method parameter names as fallback qualifiers for setter injection (parameter names aren't retained in bytecode by default), so setFoo(Foo foo2) still leaves Spring unable to resolve the ambiguity.
Memory tip: Think "Field name works, method Fails" - Spring can use a field name as a fallback qualifier (E), but not a setter parameter name (F). When in doubt, @Qualifier always wins (B, C).
Topics
Community Discussion
No community discussion yet for this question.