How to embed Jetty into Spring and make it use the same AppContext it was embedded into?

五迷三道 提交于 2019-12-04 09:25:41

问题


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?

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.


回答1:


I did this a while ago.

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.

The listener would look something like this:

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

}

and the DelegatingContextLoader does this:

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.



来源:https://stackoverflow.com/questions/3164092/how-to-embed-jetty-into-spring-and-make-it-use-the-same-appcontext-it-was-embedd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!