1、引入maven依赖
org.apache.tomcat.embed tomcat-embed-core8.5.16 org.springframework spring-web5.0.4.RELEASE compile org.springframework spring-webmvc5.0.4.RELEASE compile org.apache.tomcat tomcat-jasper8.5.16
2、加载SpringMVCDispatcherServlet
AbstractAnnotationConfigDispatcherServletInitializer这个类负责配置DispatcherServlet、初始化Spring MVC容器和Spring容器。getRootConfigClasses()方法用于获取Spring应用容器的配置文件,这里我们给定预先定义的RootConfig.class;getServletConfigClasses负责获取Spring MVC应用容器,这里传入预先定义好的WebConfig.class;getServletMappings()方法负责指定需要由DispatcherServlet映射的路径,这里给定的是"/",意思是由DispatcherServlet处理所有向该应用发起的请求。
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// 加载根容器
protected Class>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class[] { RootConfig.class };
}
// 加载SpringMVC容器
protected Class>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
// SpringMVCDispatcherServlet 拦截的请求 /
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
3、加载SpringMVC容器
正如可以通过多种方式配置DispatcherServlet一样,也可以通过多种方式启动Spring MVC特性。原来我们一般在xml文件中使用
@Configuration
@EnableWebMvc
@ComponentScan("com.wangcj.controller")
public class WebConfig extends WebMvcConfigurerAdapter {
}
4、RootConfig容器
@Configuration
@ComponentScan(basePackages = "com.wangcj")
public class RootConfig {
}
5、运行代码
public static void main(String[] args) throws ServletException, LifecycleException {
start();
}
public static void start() throws ServletException, LifecycleException {
// 创建Tomcat容器
Tomcat tomcatServer = new Tomcat();
// 端口号设置
tomcatServer.setPort(9090);
// 读取项目路径
StandardContext ctx = (StandardContext) tomcatServer.addWebapp("/", new File("src/main").getAbsolutePath());
// 禁止重新载入
ctx.setReloadable(false);
// class文件读取地址
File additionWebInfClasses = new File("target/classes");
// 创建WebRoot
WebResourceRoot resources = new StandardRoot(ctx);
// tomcat内部读取Class执行
resources.addPreResources(
new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
tomcatServer.start();
// 异步等待请求执行
tomcatServer.getServer().await();
}



