Simple Spring,将ClasspathApplicationContext用于独立应用程序,如何重用?

如果我有一个独立的主应用程序。 说20节课。 它们都可能需要随时与spring配置(ApplicationContext)定义的bean接口。 我将在主应用程序入口点引导类路径应用程序上下文。 但是,如何重用已经实例化的bean?

例如,将ClasspathApplicationContext设置为单例似乎是一种糟糕的方法,但这就是想法。

我以为我已经看过GlobalContextLocator或类似的东西,但没有看到如何使用它的例子。

有很多方法可以做到这一点。 您最好的参考是:

http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#context-introduction

您需要查看的特定类是SingletonBeanFactoryLocator和ContextSingletonBeanFactoryLocator。

如果使用SingletonBeanFactoryLocator,则可以使用以下内容查找bean:

BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance(); BeanFactoryReference bf = bfl.useBeanFactory("com.mycompany.myapp"); MyClass zed = bf.getFactory().getBean("mybean"); 

在Javadocs中有一个非常好的解释:

http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.html

另外,为了清楚起见,请确保配置文件位于应用程序的类路径中,否则查找将失败。