gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:00:27 24 4
gpt4 key购买 nike

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

事实上,在外部上下文中,我有几个类似守护进程的 bean 及其依赖项。 Jetty 内部的 Controller 使用相同的依赖项,因此我希望避免在 Jetty 内部和外部重复它们。

最佳答案

我不久前做过这个。

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

}

有点乱,可能可以改进,但这对我有用。

关于spring - 如何将 Jetty 嵌入 Spring 并使其使用嵌入的相同 AppContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3164092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com