简单的 Spring,将 ClasspathApplicationContext 用于独立应用程序,如何重用?

Ber*_*own 5 java cron spring inversion-of-control jakarta-ee

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

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

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

Jon*_*Jon 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");
Run Code Online (Sandbox Code Playgroud)

Javadocs 对此有很好的详细解释:

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

另外,需要明确的是,请确保配置文件位于应用程序的类路径中,否则查找将失败。