Spring 3 class to hold and return a single bean in

2019-09-04 23:33发布

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?

1条回答
倾城 Initia
2楼-- · 2019-09-05 00:16

Assume your method getGlobalInstance is in the class, which is also a spring bean, you can do this:

class MyBeanHolder {
@Autowired
ApplicationContext applicationContext;

  public MyBean getGlobalInstance() {
    return applicationContext.getBean(MyBean.class);
  }
}

Otherwise you can implement the interface ApplicationContextAware to get the application context, where you can find you bean with getBean

查看更多
登录 后发表回答