如何将Jetty嵌入到Spring中,并使其使用与嵌入的相同的AppContext? [英] How to embed Jetty into Spring and make it use the same AppContext it was embedded into?

查看:85
本文介绍了如何将Jetty嵌入到Spring中,并使其使用与嵌入的相同的AppContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Spring ApplicationContext where I declare Jetty server bean and start it. Inside Jetty I have a DispatcherServlet and a couple of controllers. How to make that DispatcherServlet and its controllers use beans from the same ApplicationContext where Jetty is declared?

实际上,在外部环境中,我有几个类似守护程序的bean及其依赖项. Jetty内部的控制器使用相同的依赖项,因此,我想避免在Jetty内部和外部复制它们.

In fact, in that outer context I have a couple of daemon-like beans and their dependencies. Controllers inside Jetty use the same dependencies, so I'd like to avoid duplicating them inside and outside Jetty.

推荐答案

我前一阵子做了.

Spring的文档建议您使用ContextLoaderListener来加载servlet的应用程序上下文.代替这个Spring类,使用您自己的侦听器.这里的关键是,可以在Spring配置中定义您的自定义侦听器,并且可以知道在其中定义的应用程序上下文.因此,它无需加载新的应用程序上下文,而只是返回该上下文.

Spring's documentation suggests that you use a ContextLoaderListener to load the application context for servlets. Instead of this Spring class, use your own listener. The key thing here is that your custom listener can be defined in the Spring config, and can be aware of the application context it's defined in; so instead of loading a new application context, it just returns that context.

监听器看起来像这样:

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

}

这有点混乱,可能可以改进,但这确实对我有用.

It's a bit messy, and can probably be improved, but this did work for me.

这篇关于如何将Jetty嵌入到Spring中,并使其使用与嵌入的相同的AppContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆