【问题标题】:How to embed Jetty into Spring and make it use the same AppContext it was embedded into?如何将 Jetty 嵌入 Spring 并使其使用嵌入的相同 AppContext?
【发布时间】:2011-03-10 23:54:37
【问题描述】:

我有一个 Spring ApplicationContext,我在其中声明 Jetty 服务器 bean 并启动它。在 Jetty 内部,我有一个 DispatcherServlet 和几个控制器。如何让 DispatcherServlet 及其控制器使用声明 Jetty 的同一 ApplicationContext 中的 bean?

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

【问题讨论】:

    标签: spring spring-mvc jetty embedded-jetty


    【解决方案1】:

    我不久前做过。

    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 not initialized 异常,因为GWAC 没有被刷新,但是当我在上面调用refresh() 时,我得到了关于第二次调用后处理器的异常。因此,我没有使用GWAC,而是创建了一个类WrapperWebApplicationContext,它将所有调用委托给在构造函数中传递的ApplicationContext。现在它完美地工作了。另外,我覆盖了ContextLoaderListenercreateWebApplicationContext - 这样就不需要使用ContextLoader 类。
    • 好的。我难住了。如何让 servlet 容器使用您在 spring 配置中定义的 Listener bean,而不是创建一个对 applicationContext/beanFactory 一无所知的新实例?
    猜你喜欢
    • 2016-02-22
    • 2015-05-08
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多