2V0-72.22PSE · Question #71
Refer to the exhibit. How can a Spring Bean be created from this LegacySingleton class?
The correct answer is A. Call LegacySingleton.getInstance() from within a @Bean method and return the instance. Option A is correct because a @Bean method in a @Configuration class acts as a factory - it simply needs to return an instance that Spring will manage. Since LegacySingleton uses the classic Singleton pattern (private constructor, static getInstance() factory method), calling…
Question
Refer to the exhibit. How can a Spring Bean be created from this LegacySingleton class?
Exhibit
Options
- ACall LegacySingleton.getInstance() from within a @Bean method and return the instance.
- BReturn an instance of LegacySingleton using the new keyword from a @Bean method.
- CIt is not possible without modifying the LegacySingleton class, the constructor must be public.
- DModify the LegacySingleton class by adding the @Autowired annotation to the instance variable.
How the community answered
(19 responses)- A84% (16)
- C11% (2)
- D5% (1)
Explanation
Option A is correct because a @Bean method in a @Configuration class acts as a factory - it simply needs to return an instance that Spring will manage. Since LegacySingleton uses the classic Singleton pattern (private constructor, static getInstance() factory method), calling LegacySingleton.getInstance() inside a @Bean method and returning the result is exactly how you bridge a legacy Singleton into the Spring context.
B is wrong because the Singleton pattern's constructor is private - using new LegacySingleton() won't compile. C is wrong because no modification to LegacySingleton is needed at all; the @Bean method approach in option A works as-is. D is wrong because @Autowired is for injecting dependencies into a class, not for registering a class as a bean - adding it to an instance variable inside LegacySingleton would have no effect here.
Memory tip: Think of @Bean methods as Spring "wrappers" - they can call any code that returns an object, making them perfect for adapting legacy patterns (like Singletons or static factories) into the Spring ecosystem without touching the original class.
Topics
Community Discussion
No community discussion yet for this question.
