2V0-72-22 practice question 9 of 15

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

Full set: 79 questions
Answer options
A:

A. This syntax is invalid because the result of the getBean() method call should be cast to ClientService.

B:

B. It will return a bean called ClientService regardless of its id or name.

C:

C. This syntax is invalid because the bean id must be specified as a method parameter.

D:

D. It will return a bean of the type ClientService regardless of its id or name.

Correct answer
Correct Answer:
D. D. It will return a bean of the type ClientService regardless of its id or name.
Explanation

The code fragment context.getBean(ClientService.class) uses a version of the getBean method that retrieves a bean based on its type. The Spring container will search its registry for a unique bean that is an instance of ClientService. If exactly one such bean is found, it will be returned, regardless of the bean's specific ID or name defined in the configuration. This method signature, available since Spring 2.0, also provides type safety and eliminates the need for casting.

Why Incorrect

A. Since Spring 2.0, getBean(Class requiredType) returns a typed object, making an explicit cast unnecessary and this syntax valid.
B. The method retrieves a bean by its type (ClientService), not its name. The bean's name could be different (e.g., "defaultClientService").
C. The getBean() method is overloaded. While one version accepts a bean ID string, another valid version accepts a Class object.

References

1. Spring Framework Documentation, 6.1.6, "Core Technologies," Section 1.4.3. "Retrieving a Bean from the Container." This section describes the getBean() method, including the getBean(Class requiredType) variant, which finds a bean by type.

2. Spring Framework Javadoc for org.springframework.beans.factory.BeanFactory. The Javadoc for the getBean(Class requiredType) method states it returns "the unique bean instance that matches the given object type, if any."

Scroll to Top