SpringBoot-Web容器配置

SpringBoot-Web容器配置

  • Spring启动的两种方式
    • jar包方式
    • war包方式
      • 使用外部tomcat注意事项

Spring启动的两种方式

jar包方式

  • 第一种:这种方法是使用jar包的方式,这种方式使用的是内置服务器。
@SpringBootApplication
public class App  extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }
}
  • springboot 内置了tomcat,并且会自动配置 Jetty,Undertow 这些服务器。
  • 源码分析
    • 从run开始走到下面的逻辑
    • context = this.createApplicationContext(); 生成容器根据环境会返回AnnotationConfigServletWebServerApplicationContext这个容器。
    • refresh(context); 会一直到 容器的refresh();相比较Spring这个refresh() 多了一个onRefresh();
    • onRefresh();
    • createWebServer();生成Web容器
WebServer webServer = this.webServer;
ServletContext servletContext = this.getServletContext();
//如果我们使用的是jar启动,那么上面两个参数都是null,就会调用getWebServer()
if (webServer == null && servletContext == null) {
	ServletWebServerFactory factory = this.getWebServerFactory();
	this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
	}
  • getWebServer();会找到对应的是WebServerFactory来启动服务器。
  • 如何确定使用哪一个服务器?
    • 查看ServletWebServerFactoryConfiguration这个配置类
    • 在加载每个服务器工厂类的时候都会先去判断是不是没有其他的类文件,以及是不是没有其他的ServletWebServerFactory Bean。也就是说只会被加载一个,tomcat是内置的,而且顺序是第一个,如果想要配置其他的服务器那么就需要把内置的tomcat 移除。
    • 在使用jar启动的时候,因为是springboot容器拥有tomcat,那么 原本实现WebApplicationInitializer接口的onStartup 并不会因为servlet3+的协议而启动,不过spring做了封装,可以去实现ServletContextInitializer这个接口,并且把这个类@Bean。

war包方式

  • 第二种实现方式:继承SpringBootServletInitializer这个类,这个类实际上是实现了WebApplicationInitializer,由于servlet 3+ 协议会主动调用onStartup()。后面的源码和上面差不多,只是会在createWebServer()的时候,servletContext 不为空,不会走创建逻辑。
@SpringBootApplication
public class App  extends SpringBootServletInitializer{
    //spring boot 自动配置原理
    //yml语法+解析
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return super.configure(builder).sources(App.class);
    }
}

使用外部tomcat注意事项

  • pom文件要加上 < packaging > war < /packaging >
  • web.xml文件需要存在。

你可能感兴趣的:(Spring,spring,spring,boot,tomcat)