简单的 Spring,将 ClasspathApplicationContext 用于独立应用程序,如何重用? [英] Simple Spring, use of ClasspathApplicationContext for standalone apps, how to reuse?

查看:44
本文介绍了简单的 Spring,将 ClasspathApplicationContext 用于独立应用程序,如何重用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a standalone main application. Say 20 classes. They all may need to interface with the beans defined by the spring configuration (ApplicationContext) at any time. I would bootstrap the classpath application context at the main application entry point. But how do you reuse the already instantiated beans?

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

For example, it seems like a bad approach to setup the ClasspathApplicationContext as a singleton, but that would be the idea.

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

I thought I had seen a GlobalContextLocator or something along those lines but didn't seen an example on how to use it.

推荐答案

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

There are a number of ways to do it. Your best reference is here:

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

您需要查看的具体类是 SingletonBeanFactoryLocator 和 ContextSingletonBeanFactoryLocator.

and the specific classes you need to look at are SingletonBeanFactoryLocator and ContextSingletonBeanFactoryLocator.

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

If you use the SingletonBeanFactoryLocator you can use the following to look up beans:

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

Javadocs 中有很好的解释:

There is a very good explanation of this in detail in the Javadocs:

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

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

Also, just to be clear, make sure that the config file is in your classpath for your application, otherwise the lookup will fail.

这篇关于简单的 Spring,将 ClasspathApplicationContext 用于独立应用程序,如何重用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆