我有一个Spring ApplicationContext,我在其中声明了Jetty服务器bean并启动它。在Jetty里面我有一个DispatcherServlet和几个控制器。如何使DispatcherServlet及其控制器使用来自声明Jetty的同一ApplicationContext中的bean?
事实上,在那个外部上下文中,我有几个类似守护进程的bean及其依赖项。 Jetty中的控制器使用相同的依赖关系,所以我想避免在Jetty内外重复它们。
答案 0 :(得分:5)
我刚才这样做了。
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);
}
}
它有点乱,可能会有所改进,但这对我有用。