提问者:小点点

在Springmvc中使用Webapplation初始化器注入调度器servlet


我必须动态地加载调度器servlet及其配置文件。我正在研究使用webapplication ation和初始化器注入调度器servlet的概念,这是Spring的最新开发。以下文档给出了概述:http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer.html

我正在尝试做一个基本的设置,但它就是不起作用。我无法理解从哪里开始摆脱传统的Spring开发。有人能举个例子来解释我如何使用这种新机制吗?我使用了以下代码:

 public class MyWebAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext container) {
  // Create the 'root' Spring application context
  AnnotationConfigWebApplicationContext rootContext =
    new AnnotationConfigWebApplicationContext();
  rootContext.register(AppConfig.class);

  // Manage the lifecycle of the root application context
  container.addListener(new ContextLoaderListener(rootContext));

  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext =
    new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(DispatcherConfig.class);

  // Register and map the dispatcher servlet
  ServletRegistration.Dynamic dispatcher =
    container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
  dispatcher.setLoadOnStartup(1);
  dispatcher.addMapping("/");
}

}

此外,如果我们动态注入调度器servlet,这是否意味着调度器servlet在Web容器(tomcat)启动期间加载?


共1个答案

匿名用户

尝试将映射从/更改为调度("/*")

/已经映射到Tomcat的默认Servlet,因此addMaps("/")不会做任何事情。

这仅适用于您使用的是Tomcat版本

在Tomcat启动时,tomcat将查找实现ServletContainerFirst alizer的类。在Spring中,它将找到类SpringServletContainerFirst alizer。这个类将被提供一组Tomcat加载的类(基本上是您的所有类)。然后它将查找实现WebApplicationNovalizer的任何一个,并在它们上调用onStartup()。这就是您上面发布的方法发挥作用的地方,初始化上下文和Spring的'DispatcherServlet。