2V0-72.22PSE · Question #2
Refer to the exhibit. It is a Java code fragment from a Spring application. Which statement is true with regard to the above example? (Choose the best answer.)
The correct answer is D. It will return a bean of the type ClientService regardless of its id or name. Option D is correct because the code uses the type-safe overload context.getBean(ClientService.class), which instructs Spring to locate a bean by type rather than by its id or name. Spring searches its application context for any registered bean that matches - or is assignable…
Question
Refer to the exhibit. It is a Java code fragment from a Spring application. Which statement is true with regard to the above example? (Choose the best answer.)
Options
- AThis syntax is invalid because the result of the getBean() method call should be cast to
- BIt will return a bean called ClientService regardless of its id or name.
- CThis syntax is invalid because the bean id must be specified as a method parameter.
- DIt will return a bean of the type ClientService regardless of its id or name.
How the community answered
(37 responses)- A3% (1)
- B5% (2)
- D92% (34)
Explanation
Option D is correct because the code uses the type-safe overload context.getBean(ClientService.class), which instructs Spring to locate a bean by type rather than by its id or name. Spring searches its application context for any registered bean that matches - or is assignable to - the ClientService type and returns it directly.
Why the distractors are wrong:
- A is wrong - The
getBean(Class<T>)overload is generic and returns a typed result (ClientService), so no explicit cast is necessary. A cast would only be required when using the oldergetBean(String name)overload, which returnsObject. - B is wrong - The method does not search by the string "ClientService". It searches by the type
ClientService.class. These are fundamentally different lookups; the bean's id or name is completely ignored. - C is wrong - Providing a bean id is not mandatory here. The
getBean(Class<T>)overload is specifically designed to work without an id, using type matching alone. An id would only be needed if you had multiple beans of the same type and needed to distinguish between them.
Memory tip: The .class suffix is your clue - getBean(ClientService.class) means "find me a ClientService," while getBean("myService") means "find me the bean named myService." When you see .class, think type, not name.
Topics
Community Discussion
No community discussion yet for this question.