5

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

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

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

4

1 回答 1

4

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

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

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

于 2009-04-01T23:25:05.603 回答