如何将Jetty嵌入Spring并使其使用嵌入的相同AppContext?

Fix*_*int 9 spring jetty spring-mvc embedded-jetty

我有一个Spring ApplicationContext,我在其中声明了Jetty服务器bean并启动它.在Jetty里面我有一个DispatcherServlet和几个控制器.如何使DispatcherServlet及其控制器使用来自声明Jetty的同一ApplicationContext的bean?

事实上,在那个外部上下文中,我有几个类似守护进程的bean及其依赖项.Jetty中的控制器使用相同的依赖关系,所以我想避免在Jetty内外重复它们.

Ric*_*arn 5

我刚才这样做了.

Spring的文档建议您使用a 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

这样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);
    }

}
Run Code Online (Sandbox Code Playgroud)

它有点乱,可能会有所改进,但这对我有用.

  • 谢谢!经过一些修改后我解决了我的问题。通过这个解决方案,我得到了“ApplicationEventMulticaster not初始化”异常,因为“GWAC”没有刷新,但是当我对其调用“refresh()”时,我得到了关于第二次调用后处理器的异常。因此,我没有使用“GWAC”,而是创建了一个“WrapperWebApplicationContext”类,它将所有调用委托给构造函数中传递的“ApplicationContext”。现在它工作得很好。另外,我重写了 `ContextLoaderListener` 的 `createWebApplicationContext` - 这样就不需要使用 `ContextLoader` 类。 (2认同)