是否有一种方法可以在Spring应用程序中静态/全局地请求ApplicationContext的副本?

假设主类启动并初始化了应用程序上下文,它是否需要通过调用堆栈向下传递给任何需要它的类,或者类是否有一种方法来请求先前创建的上下文?(我假设它必须是单例的?)


当前回答

这里有一个很好的方法(不是我的,原始参考在这里: http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html

我使用过这种方法,效果很好。基本上,它是一个简单的bean,包含对应用程序上下文的(静态)引用。通过在spring配置中引用它来初始化它。

看看原来的裁判,非常清楚。

其他回答

这里有一个很好的方法(不是我的,原始参考在这里: http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html

我使用过这种方法,效果很好。基本上,它是一个简单的bean,包含对应用程序上下文的(静态)引用。通过在spring配置中引用它来初始化它。

看看原来的裁判,非常清楚。

我相信你可以使用SingletonBeanFactoryLocator。beanRefFactory.xml文件将保存实际的applicationContext,它将像这样:

<bean id="mainContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
     <constructor-arg>
        <list>
            <value>../applicationContext.xml</value>
        </list>
     </constructor-arg>
 </bean>

从应用上下文中获取bean的代码是这样的:

BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bf = bfl.useBeanFactory("mainContext");
SomeService someService = (SomeService) bf.getFactory().getBean("someService");

Spring团队不鼓励使用这个类和yadayada,但它很适合我使用它的地方。

在Spring应用程序中有许多获取应用程序上下文的方法。这些因素如下:

通过ApplicationContextAware: 进口org.springframework.beans.BeansException; 进口org.springframework.context.ApplicationContext; 进口org.springframework.context.ApplicationContextAware; 公共类AppContextProvider实现了ApplicationContextAware { private ApplicationContext; @Override setApplicationContext(ApplicationContext)抛出BeansException { 这一点。applicationContext = applicationContext; } }

这里setApplicationContext(ApplicationContext ApplicationContext)方法将获得ApplicationContext

ApplicationContextAware: 接口,由希望被通知的任何对象实现 它运行的ApplicationContext的。实现此接口 例如,当一个对象需要访问一组 合作bean。

通过Autowired的: @ autowired private ApplicationContext;

这里@Autowired关键字将提供applicationContext。自动连线有一些问题。这将在单元测试时产生问题。

看一下ContextSingletonBeanFactoryLocator。它提供静态访问器来获取Spring的上下文,假设它们已经以某种方式注册。

它并不漂亮,而且可能比您想要的还要复杂,但它是有效的。

即使在添加了@Autowire之后,如果你的类不是一个RestController或Configuration class, applicationContext对象仍然是空的。尝试用下面创建新类,它工作正常:

@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

然后,你可以在同一个类中根据你的需要实现一个getter方法,比如通过:

    applicationContext.getBean(String serviceName,Interface.Class)