在 Servlet 3.0+ 环境,可以以编程方式配置。WebApplicationInitializer 接口,可以确保检测到基于代码的配置和用来自动初始化基于 Servlet 3 的容器。
1、引用javax.servlet包
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
2、实现AbstractDispatcherServletInitializer接口
public class MyDispatcherServletInitializer extends AbstractDispatcherServletInitializer {
protected WebApplicationContext createServletApplicationContext() {
XmlWebApplicationContext cxt = new XmlWebApplicationContext();
cxt.setConfigLocation("/WEB-INF/springmvc-servlet.xml");
return cxt;
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
Spring 自定义 AbstractDispatcherServletInitializer无法访问,别忘记引用 javax.servlet包