在Servlet 3.0规范发布后,几乎可以不使用xml配置Servlet容器。为此,Servlet规范中提供了ServletContainerInitializer
。在这个类中,您可以像在web.xml
中传统地注册过滤器、监听器、Servlet等。
Spring提供了一个实现SpringServletContainerInitializer
的工具,它知道如何处理WebApplicationInitializer
类。Spring还提供了一些基础类以便扩展从而让您的生活更轻松。AbstractAnnotationConfigDispatcherServletInitializer
就是其中之一,它会注册一个ContextLoaderlistener
(可选)和一个DispatcherServlet
,并允许您轻松添加要加载到这两个类中的配置类,并对DispatcherServlet
应用过滤器,并提供Servlet映射。
WebMvcConfigurerAdapter
用于配置Spring MVC,替换被DispatcherServlet
加载的XML文件来配置Spring MVC。应该使用@Configuration
类来使用WebMvcConfigurerAdapter
。
@Configuration
@EnableWebMvc
public class WebConfiguration
extends WebMvcConfigurerAdapter implements WebApplicationInitializer
{ ... }
我不建议混合使用它们,因为它们基本上是两个不同的关注点。第一个是用于配置Servlet容器,而后者用于配置Spring MVC。
你会想把它们分成两个类。
用于配置目的。
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter { ... }
用于引导应用程序的启动过程。
public class MyWebApplicationInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer
{
protected Class<?>[] getRootConfigClasses() {
return new Class[] {RootConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfiguration .class};
}
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
另一个优点是,现在您可以使用Spring提供的便捷类,而不是手动配置 DispatcherServlet 和/或
ContextLoaderListener 。
extends WebMvcConfigurerAdapter and implements WebApplicationInitializer
)。 - Manuel JordanRootConfig.class
文件? - zygimantus要从头开始,值得研究一下servlet容器的启动方式。
因此要开始,SpringServletContainerInitializer必须找到正确的实现了 WebApplicationInitializer的类。实现方法有两种:
希望这能帮到您。