Let's say I have a spring bean I want to use through out my application, but because it's legacy code I can't make every single class I want to use it in a @Component
or any kind of bean because the class is being manually instantiated through out the project, so I can't just @Autowire it where I want it.
How can I create a wrapper class for a spring bean I want to reuse configured as below, so that it will do nothing other than return the instance of the bean registered on the application context?
@Service("myBean")
public class MyBean {
Basically I'm looking for something like MyBeanHolder.java
with a method like:
public MyBean getGlobalInstance() {
//return my global instance of MyBean
}
So this way, anywhere I want to use MyBean, I can fetch the instance via this getGlobalInstance()
method.
How can I achieve this running Spring 3.X?
Assume your method
getGlobalInstance
is in the class, which is also a spring bean, you can do this:Otherwise you can implement the interface
ApplicationContextAware
to get the application context, where you can find you bean withgetBean