Simple Spring,对于独立应用使用ClasspathApplicationContext,如何重用? [英] Simple Spring, use of ClasspathApplicationContext for standalone apps, how to reuse?

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

问题描述

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



例如,看起来像一个糟糕的方法来设置ClasspathApplicationContext作为单例,但这将是一个想法。 / p>

我以为我看过一个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



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


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?

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

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

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

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");

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.

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

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