spring boot如何启动的Tomcat

本文主要介绍spring boot如何启动tomcat的,spring boot的版本为2.1.8.RELEASE

一、从main方法开始

public class TestApplication {

   public static void main(String[] args) {
      SpringApplication.run(TestApplication.class, args);
   }

}

直接去查看run方法的源码,发现调用的是SpringApplication里面的如下方法:

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
        return run(new Class[]{primarySource}, args);
    }

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args){
        return (new SpringApplication(primarySources)).run(args);
    }

继续往下跟踪发现最终调用的是如下 的run()

public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
        //设置系统属性【java.awt.headless】,初始化是该属性值默认为true,是启用模式
        this.configureHeadlessProperty();

        //通过*SpringFactoriesLoader*检索*META-INF/spring.factories*,
       //找到声明的所有SpringApplicationRunListener的实现类并将其实例化,
       //之后逐个调用其started()方法,广播SpringBoot要开始执行了
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        
        //发不应用启动事件
        listeners.starting();

        Collection exceptionReporters;
        try {
            //初始化参数
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
             //创建并配置当前SpringBoot应用将要使用的Environment(包括配置要使用的PropertySource以及Profile),
            //并遍历调用所有的SpringApplicationRunListener的environmentPrepared()方法,广播Environment准备完毕。
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
            //打印Banner
            Banner printedBanner = this.printBanner(environment);
            //创建应用上下文
            context = this.createApplicationContext();
            //通过*SpringFactoriesLoader*检索*META-INF/spring.factories*,获取并实例化异常分析器
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            //为ApplicationContext加载environment,之后逐个执行ApplicationContextInitializer的initialize()方法来进一步封装ApplicationContext,
            //并调用所有的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一个空的contextPrepared()方法】,
            //之后初始化IoC容器,并调用SpringApplicationRunListener的contextLoaded()方法,广播ApplicationContext的IoC加载完成,
            //这里就包括通过**@EnableAutoConfiguration**导入的各种自动配置类。
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            //刷新上下文
            this.refreshContext(context);
            //再一次刷新上下文,其实是空方法,可能是为了后续扩展。
            this.afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }

            //发布应用已经启动的事件
            listeners.started(context);
            //遍历所有注册的ApplicationRunner和CommandLineRunner,并执行其run()方法。
            //我们可以实现自己的ApplicationRunner或者CommandLineRunner,来对SpringBoot的启动过程进行扩展。
            this.callRunners(context, applicationArguments);
        } catch (Throwable var10) {
            this.handleRunFailure(context, var10, exceptionReporters, listeners);
            throw new IllegalStateException(var10);
        }

        try {
            //应用已经启动完成的监听事件
            listeners.running(context);
            return context;
        } catch (Throwable var9) {
            this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
            throw new IllegalStateException(var9);
        }
    }

其实这个方法的可以总结为如下步骤:

1.配置属性

2.获取监听器,发布应用开始启动事件

3.初始化输入参数

4.配置环境,输出Banner

5.创建上下文

6.预处理上下文

7.刷新上下文

8.再次刷新上下文

9.发布应用已启动的事件

10.发布应用已启动完成的事件

如上的代码如果只是分析tomcat的话就只需要关注两个内容:1.上下文是如何创建的 2.上下文是如何刷新的,分别对应的方法是

createApplicationContext()和refreshContext(context),分别看一下这两个方法:

protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                switch(this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
                    break;
                case REACTIVE:
                    contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
                    break;
                default:
                    contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
                }
            } catch (ClassNotFoundException var3) {
                throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
            }
        }

        return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
    }

这是根据webApplicationType来判断创建哪种类型的servlet,代码中分别对应的是Web类型(SERVLET),响应式Web类型(REACTIVE),非Web类型(default),我们创建的是Web类型,所以实现的是org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext类型的

通过这个类图我们可以知道,这个类继承的是 ServletWebServerApplicationContext,这就是我们真正的主角,而这个类最终是继承了 AbstractApplicationContext,了解完创建上下文的情况后,我们再来看看刷新上下文,相关代码如下:

private void refreshContext(ConfigurableApplicationContext context) {
        this.refresh(context);
        if (this.registerShutdownHook) {
            try {
                context.registerShutdownHook();
            } catch (AccessControlException var3) {
            }
        }

}

protected void refresh(ApplicationContext applicationContext) {
        Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
        ((AbstractApplicationContext)applicationContext).refresh();
}

这段代码中还是直接调用的当前类的refresh方法,最后是强转成父类 AbstractApplicationContext 调用其 refresh()方法,该代码如下:

public void refresh() throws BeansException, IllegalStateException {
        synchronized(this.startupShutdownMonitor) {
            this.prepareRefresh();
            ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
            this.prepareBeanFactory(beanFactory);

            try {
                this.postProcessBeanFactory(beanFactory);
                this.invokeBeanFactoryPostProcessors(beanFactory);
                this.registerBeanPostProcessors(beanFactory);
                this.initMessageSource();
                this.initApplicationEventMulticaster();
                this.onRefresh();
                this.registerListeners();
                this.finishBeanFactoryInitialization(beanFactory);
                this.finishRefresh();
            } catch (BeansException var9) {
                if (this.logger.isWarnEnabled()) {
                    this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
                }

                this.destroyBeans();
                this.cancelRefresh(var9);
                throw var9;
            } finally {
                this.resetCommonCaches();
            }

        }
}

这里我们看到 onRefresh()方法是调用其子类的实现,根据我们上文的分析,我们这里的子类是 ServletWebServerApplicationContext。

protected void onRefresh() {
        super.onRefresh();

        try {
            this.createWebServer();
        } catch (Throwable var2) {
            throw new ApplicationContextException("Unable to start web server", var2);
        }
}

private void createWebServer() {
        WebServer webServer = this.webServer;
        ServletContext servletContext = this.getServletContext();
        if (webServer == null && servletContext == null) {
            ServletWebServerFactory factory = this.getWebServerFactory();
            this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
        } else if (servletContext != null) {
            try {
                this.getSelfInitializer().onStartup(servletContext);
            } catch (ServletException var4) {
                throw new ApplicationContextException("Cannot initialize servlet context", var4);
            }
        }

        this.initPropertySources();
}

到这里才是真正的启动web服务,createWebServer()就是启动 web 服务,但是还没有真正启动 Tomcat,既然 webServer 是通过 ServletWebServerFactory 来获取的,我们就来看看这个工厂的真面目。

 

二、走进Tomcat内部

通过以上得知工厂类是一个接口,具体的服务的实现是由各个子类各自实现的,下面就来看下TomcatServletWebServerFactory.getWebServer()的实现

public WebServer getWebServer(ServletContextInitializer... initializers) {
        Tomcat tomcat = new Tomcat();
        File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
        tomcat.setBaseDir(baseDir.getAbsolutePath());
        Connector connector = new Connector(this.protocol);
        tomcat.getService().addConnector(connector);
        this.customizeConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);
        this.configureEngine(tomcat.getEngine());
        Iterator var5 = this.additionalTomcatConnectors.iterator();

        while(var5.hasNext()) {
            Connector additionalConnector = (Connector)var5.next();
            tomcat.getService().addConnector(additionalConnector);
        }

        this.prepareContext(tomcat.getHost(), initializers);
        return this.getTomcatWebServer(tomcat);
}

通过以上可以看到最核心的两件事:1.把connector对象添加到Tomcat,2configureEngine(),再来看下这个Engine具体做了什么

tomcat.getEngine()

public Engine getEngine() {
        Service service = this.getServer().findServices()[0];
        if (service.getContainer() != null) {
            return service.getContainer();
        } else {
            Engine engine = new StandardEngine();
            engine.setName("Tomcat");
            engine.setDefaultHost(this.hostname);
            engine.setRealm(this.createDefaultRealm());
            service.setContainer(engine);
            return engine;
        }
}

通过以上我们可以知道这个engine是个容器,如下:

public interface Engine extends Container {
    String getDefaultHost();

    void setDefaultHost(String var1);

    String getJvmRoute();

    void setJvmRoute(String var1);

    Service getService();

    void setService(Service var1);
}

再继续看,我们可以找到Container

通过以上我们可以看到4个接口,Engine,Host,Context,Wrapper

/**
 If used, an Engine is always the top level Container in a Catalina
 * hierarchy. Therefore, the implementation's setParent() method
 * should throw IllegalArgumentException.
 *
 * @author Craig R. McClanahan
 */
publicinterface Engine extends Container {
    //省略代码
}
/**
 *

 * The parent Container attached to a Host is generally an Engine, but may
 * be some other implementation, or may be omitted if it is not necessary.
 *

 * The child containers attached to a Host are generally implementations
 * of Context (representing an individual servlet context).
 *
 * @author Craig R. McClanahan
 */
public interface Host extends Container {
//省略代码

}
/***

 * The parent Container attached to a Context is generally a Host, but may
 * be some other implementation, or may be omitted if it is not necessary.
 *

 * The child containers attached to a Context are generally implementations
 * of Wrapper (representing individual servlet definitions).
 *

 *
 * @author Craig R. McClanahan
 */
public interface Context extends Container, ContextBind {
    //省略代码
}
/**

 * The parent Container attached to a Wrapper will generally be an
 * implementation of Context, representing the servlet context (and
 * therefore the web application) within which this servlet executes.
 *

 * Child Containers are not allowed on Wrapper implementations, so the
 * addChild() method should throw an
 * IllegalArgumentException.
 *
 * @author Craig R. McClanahan
 */
publicinterface Wrapper extends Container {

    //省略代码
}

根据以上的意思,我们可以知道Engine是最高级别的容器,其子容器是Host,Host的子容器是Context,Wrapper是Context的子容器,这四个容器之间的关系为Engine>Host>Context>Wrapper

public class Tomcat{
        //设置连机器
       public void setConnector(Connector connector) {
        Service service = this.getService();
        boolean found = false;
        Connector[] var4 = service.findConnectors();
        int var5 = var4.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            Connector serviceConnector = var4[var6];
            if (connector == serviceConnector) {
                found = true;
            }
        }

        if (!found) {
            service.addConnector(connector);
        }

    }

    //获取service
    public Service getService() {
        return this.getServer().findServices()[0];
    }
    
    //设置host容器
    public void setHost(Host host) {
        Engine engine = this.getEngine();
        boolean found = false;
        Container[] var4 = engine.findChildren();
        int var5 = var4.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            Container engineHost = var4[var6];
            if (engineHost == host) {
                found = true;
            }
        }

        if (!found) {
            engine.addChild(host);
        }

    }
    
    //获取engine容器
    public Engine getEngine() {
        Service service = this.getServer().findServices()[0];
        if (service.getContainer() != null) {
            return service.getContainer();
        } else {
            Engine engine = new StandardEngine();
            engine.setName("Tomcat");
            engine.setDefaultHost(this.hostname);
            engine.setRealm(this.createDefaultRealm());
            service.setContainer(engine);
            return engine;
        }
    }

    //获取server
    public Server getServer() {
        if (this.server != null) {
            return this.server;
        } else {
            System.setProperty("catalina.useNaming", "false");
            this.server = new StandardServer();
            this.initBaseDir();
            ConfigFileLoader.setSource(new CatalinaBaseConfigurationSource(new File(this.basedir), (String)null));
            this.server.setPort(-1);
            Service service = new StandardService();
            service.setName("Tomcat");
            this.server.addService(service);
            return this.server;
        }
    }

    //添加context容器
    public Context addContext(Host host, String contextPath, String dir) {
        return this.addContext(host, contextPath, contextPath, dir);
    }

    public Context addContext(Host host, String contextPath, String contextName, String dir) {
        this.silence(host, contextName);
        Context ctx = this.createContext(host, contextPath);
        ctx.setName(contextName);
        ctx.setPath(contextPath);
        ctx.setDocBase(dir);
        ctx.addLifecycleListener(new Tomcat.FixContextListener());
        if (host == null) {
            this.getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }

        return ctx;
    }

    //添加wrapper容器
    public Wrapper addServlet(String contextPath, String servletName, String servletClass) {
        Container ctx = this.getHost().findChild(contextPath);
        return addServlet((Context)ctx, servletName, servletClass);
    }

    public static Wrapper addServlet(Context ctx, String servletName, String servletClass) {
        Wrapper sw = ctx.createWrapper();
        sw.setServletClass(servletClass);
        sw.setName(servletName);
        ctx.addChild(sw);
        return sw;
    }
    
}
 

阅读 Tomcat 的 getServer()我们可以知道,Tomcat 的最顶层是 Server,Server 就是 Tomcat 的实例,一个 Tomcat 一个 Server

通过 getEngine()我们可以了解到 Server 下面是 Service,而且是多个,一个 Service 代表我们部署的一个应用,而且我们还可以知道,Engine 容器,一个 service 只有一个;根据父子关系,我们看 setHost()源码可以知道,host 容器有多个

同理,我们发现 addContext()源码下,Context 也是多个;addServlet()表明 Wrapper 容器也是多个,而且这段代码也暗示了,其实 Wrapper 和 Servlet 是一层意思。另外我们根据 setConnector 源码可以知道,连接器(Connector)是设置在 service 下的,而且是可以设置多个连接器(Connector)。

根据上面分析,我们可以小结下:Tomcat 主要包含了 2 个核心组件,连接器(Connector)和容器(Container),用图表示如下:

 

一个 Tomcat 是一个 Server,一个 Server 下有多个 service,也就是我们部署的多个应用,一个应用下有多个连接器(Connector)和一个容器(Container),容器下有多个子容器,关系用图表示如下:

Engine 下有多个 Host 子容器,Host 下有多个 Context 子容器,Context 下有多个 Wrapper 子容器。

3.总结

SpringBoot 的启动是通过 new SpringApplication()实例来启动的,启动过程主要做如下几件事情:

1. 配置属性
2. 获取监听器,发布应用开始启动事件
3. 初始化输入参数
4. 配置环境,输出 banner
5. 创建上下文
6. 预处理上下文
7. 刷新上下文
8. 再刷新上下文
9. 发布应用已经启动事件
10. 发布应用启动完成事件

而启动 Tomcat 就是在第 7 步中“刷新上下文”;Tomcat 的启动主要是初始化 2 个核心组件,连接器(Connector)和容器(Container),一个 Tomcat 实例就是一个 Server,一个 Server 包含多个 Service,也就是多个应用程序,每个 Service 包含多个连接器(Connetor)和一个容器(Container),而容器下又有多个子容器,按照父子关系分别为:Engine,Host,Context,Wrapper,其中除了 Engine 外,其余的容器都是可以有多个。

参考链接:https://mp.weixin.qq.com/s/P3a8BVuDmz_7EhkidSCAng

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值