Simple Spring, use of ClasspathApplicationContext for standalone apps, how to reuse?

后端 未结 1 339
感动是毒
感动是毒 2021-01-06 10:01

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

相关标签:
1条回答
  • 2021-01-06 11:05

    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.

    0 讨论(0)
提交回复
热议问题