Spring 3类可以保存并返回单个bean实例吗? [英] Spring 3 class to hold and return a single bean instance?
问题描述
假设我有一个Spring bean,我想在整个应用程序中使用它,但是由于它是遗留代码,所以我无法使每个类都可以在@Component
或任何类型的bean中使用,因为该类是在整个项目中手动实例化的,所以我不能只在需要的地方使用@Autowire.
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.
如何为要重用的Spring bean创建包装类,如下所示,以便除了返回在应用程序上下文中注册的bean实例之外,什么都不做?
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 {
基本上,我正在使用类似方法来寻找类似MyBeanHolder.java
的东西:
Basically I'm looking for something like MyBeanHolder.java
with a method like:
public MyBean getGlobalInstance() {
//return my global instance of MyBean
}
这样,在任何我想使用MyBean的地方,我都可以通过此getGlobalInstance()
方法获取实例.
So this way, anywhere I want to use MyBean, I can fetch the instance via this getGlobalInstance()
method.
如何在Spring 3.X上运行此代码?
How can I achieve this running Spring 3.X?
推荐答案
假设您的方法getGlobalInstance
在类中,该类也是spring bean,您可以执行以下操作:
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);
}
}
否则,您可以实现接口ApplicationContextAware
以获得应用程序上下文,您可以在其中使用getBean
Otherwise you can implement the interface ApplicationContextAware
to get the application context, where you can find you bean with getBean
这篇关于Spring 3类可以保存并返回单个bean实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!