有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

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


共 (1) 个答案

  1. # 1 楼答案

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

    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

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