Springboot内置tomcat原理
springmvc注解版
打开官网关于springmvc, 已经给了两种方式。链接: Springmvc
第一种
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletCxt) {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
ac.register(AppConfig.class);
ac.refresh();
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(ac);
ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
}
}
第二种
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { App1Config.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/app1/*" };
}
}
对应的xml配置
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
原理:
ServletContainerInitializer是servlet3.0规范中引入的接口,能够让web应用程序在servlet容器启动后做一些自定义的操作。
ServletContainerInitializer 基于服务提供者接口(SPI)概念,因此你需要在你的jar包目录下添加META-INF/services/javax.servlet.ServletContainerInitializer文件,内容就是ServletContainerInitializer实现类的全限定名。
结合内置的tomcat
public class App {
public static void main(String[] args) {
Tomcat tomcat = new Tomcat();
tomcat.setPort(9999);
Connector conn = tomcat.getConnector(); // Tomcat 9.0 必须调用 Tomcat#getConnector() 方法之后才会监听端口
System.out.println("连接器设置完成: " + conn);
try {
tomcat.addWebapp("/", "D:\\boot");
tomcat.start();
tomcat.getServer().await();
} catch (LifecycleException e) {
e.printStackTrace();
}
}
}
tomcat作为servlet规范的实现者,默认会扫描classpath包下ServletContainerInitializer的类,作为入口,从而实现内置。
具体代码目录:https://github.com/peter-anything/springmvc
欢迎点赞和关注