我之前做过这个。
Spring的documentation建议您使用ContextLoaderListener
加载servlet的应用程序上下文。而不是这个Spring类,使用你自己的监听器。这里的关键是您的自定义监听器可以在Spring配置中定义,并且可以知道它定义的应用程序上下文;所以不是加载一个新的应用程序上下文,而是只返回该上下文。
听者会是这个样子:
public class CustomContextLoaderListener extends ContextLoaderListener implements BeanFactoryAware {
@Override
protected ContextLoader createContextLoader() {
return new DelegatingContextLoader(beanFactory);
}
protected BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
和DelegatingContextLoader
做到这一点:
public class DelegatingContextLoader extends ContextLoader {
protected BeanFactory beanFactory;
public DelegatingContextLoader(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext, ApplicationContext parent) throws BeansException {
return new GenericWebApplicationContext((DefaultListableBeanFactory) beanFactory);
}
}
这是一个有点乱,并且或许可以得到改善,但是这确实为我工作。
谢谢!经过一些修改,我解决了我的问题。有了这个解决方案,我得到了'ApplicationEventMulticaster'未初始化的异常,因为'GWAC'没有被刷新,但是当我调用'refresh()'时,我得到了第二次调用的后处理器的异常。 因此,我没有使用'GWAC',而是创建了一个'WrapperWebApplicationContext'类,它将所有对调用ApplicationContext的调用委托给构造函数。现在它完美地工作。 此外,我重写了'ContextLoaderListener'的'createWebApplicationContext' - 这种方式不需要使用'ContextLoader'类。 – Fixpoint 2010-07-02 10:26:56
好的。我很难过。如何让servlet容器使用您在spring配置中定义的Listener bean,而不是创建一个对applicationContext/beanFactory一无所知的新实例? – CupawnTae 2013-06-27 16:29:31