SpringBoot中怎么啟動Tomcat

概述

SpringBoot是由Pivotal團隊在2013年開始研發(fā)、2014年4月發(fā)布第一個版本的全新開源的輕量級框架。它基于Spring4.0設(shè)計,不僅繼承了Spring框架原有的優(yōu)秀特性,而且還通過簡化配置來進一步簡化了Spring應用的整個搭建和開發(fā)過程。另外SpringBoot通過集成大量的框架使得依賴包的版本沖突,以及引用的不穩(wěn)定性等問題得到了很好的解決。

為岑鞏等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務,及岑鞏網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務為成都網(wǎng)站設(shè)計、成都網(wǎng)站制作、岑鞏網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務,秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!

Tomcat

Tomcat是Apache 軟件基金會(Apache Software Foundation)的Jakarta 項目中的一個核心項目,由Apache、Sun 和其他一些公司及個人共同開發(fā)而成。由于有了Sun 的參與和支持,最新的Servlet 和JSP 規(guī)范總是能在Tomcat 中得到體現(xiàn),Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 規(guī)范。因為Tomcat 技術(shù)先進、性能穩(wěn)定,而且免費,因而深受Java 愛好者的喜愛并得到了部分軟件開發(fā)商的認可,成為目前比較流行的Web 應用服務器。

我們知道SpringBoot給我們帶來了一個全新的開發(fā)體驗,我們可以直接把web程序達成jar包,直接啟動,這就得益于SpringBoot內(nèi)置了容器,可以直接啟動,本文將以Tomcat為例,來看看SpringBoot是如何啟動Tomcat的,同時也將展開學習下Tomcat的源碼,了解Tomcat的設(shè)計。

從 Main 方法說起

用過SpringBoot的人都知道,首先要寫一個main方法來啟動

SpringBoot中怎么啟動Tomcat

我們直接點擊run方法的源碼,跟蹤下來,發(fā)下最終 的run方法是調(diào)用ConfigurableApplicationContext方法,源碼如下:

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    CollectionexceptionReporters = new ArrayList<>();
    //設(shè)置系統(tǒng)屬性『java.awt.headless』,為true則啟用headless模式支持
    configureHeadlessProperty();
    //通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,
       //找到聲明的所有SpringApplicationRunListener的實現(xiàn)類并將其實例化,
       //之后逐個調(diào)用其started()方法,廣播SpringBoot要開始執(zhí)行了
    SpringApplicationRunListeners listeners = getRunListeners(args);
    //發(fā)布應用開始啟動事件
    listeners.starting();
    try {
    //初始化參數(shù)
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
      //創(chuàng)建并配置當前SpringBoot應用將要使用的Environment(包括配置要使用的PropertySource以及Profile),
        //并遍歷調(diào)用所有的SpringApplicationRunListener的environmentPrepared()方法,廣播Environment準備完畢。
      ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
      configureIgnoreBeanInfo(environment);
      //打印banner
      Banner printedBanner = printBanner(environment);
      //創(chuàng)建應用上下文
      context = createApplicationContext();
      //通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,獲取并實例化異常分析器
      exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
          new Class[] { ConfigurableApplicationContext.class }, context);
      //為ApplicationContext加載environment,之后逐個執(zhí)行ApplicationContextInitializer的initialize()方法來進一步封裝ApplicationContext,
        //并調(diào)用所有的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一個空的contextPrepared()方法】,
        //之后初始化IoC容器,并調(diào)用SpringApplicationRunListener的contextLoaded()方法,廣播ApplicationContext的IoC加載完成,
        //這里就包括通過**@EnableAutoConfiguration**導入的各種自動配置類。
      prepareContext(context, environment, listeners, applicationArguments, printedBanner);
      //刷新上下文
      refreshContext(context);
      //再一次刷新上下文,其實是空方法,可能是為了后續(xù)擴展。
      afterRefresh(context, applicationArguments);
      stopWatch.stop();
      if (this.logStartupInfo) {
        new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
      }
      //發(fā)布應用已經(jīng)啟動的事件
      listeners.started(context);
      //遍歷所有注冊的ApplicationRunner和CommandLineRunner,并執(zhí)行其run()方法。
        //我們可以實現(xiàn)自己的ApplicationRunner或者CommandLineRunner,來對SpringBoot的啟動過程進行擴展。
      callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, listeners);
      throw new IllegalStateException(ex);
    }

    try {
    //應用已經(jīng)啟動完成的監(jiān)聽事件
      listeners.running(context);
    }
    catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, null);
      throw new IllegalStateException(ex);
    }
    return context;
  }

其實這個方法我們可以簡單的總結(jié)下步驟為 > 1. 配置屬性 > 2. 獲取監(jiān)聽器,發(fā)布應用開始啟動事件 > 3. 初始化輸入?yún)?shù) > 4. 配置環(huán)境,輸出banner > 5. 創(chuàng)建上下文 > 6. 預處理上下文 > 7. 刷新上下文 > 8. 再刷新上下文 > 9. 發(fā)布應用已經(jīng)啟動事件 > 10. 發(fā)布應用啟動完成事件

其實上面這段代碼,如果只要分析tomcat內(nèi)容的話,只需要關(guān)注兩個內(nèi)容即可,上下文是如何創(chuàng)建的,上下文是如何刷新的,分別對應的方法就是createApplicationContext() 和refreshContext(context),接下來我們來看看這兩個方法做了什么。

protected ConfigurableApplicationContext createApplicationContext(){ Class<!--?--> contextClass =this.applicationContextClass; if (contextClass ==null) { try { switch (this.webApplicationType) { case SERVLET: contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS); break; case REACTIVE: contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS); break; default: contextClass = Class.forName(DEFAULT_CONTEXT_CLASS); } } catch (ClassNotFoundException ex) { thrownew IllegalStateException( "Unable create a default ApplicationContext, " +"please specify an ApplicationContextClass", ex); } } return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass); }

這里就是根據(jù)我們的webApplicationType 來判斷創(chuàng)建哪種類型的Servlet,代碼中分別對應著Web類型(SERVLET),響應式Web類型(REACTIVE),非Web類型(default),我們建立的是Web類型,所以肯定實例化 DEFAULT_SERVLET_WEB_CONTEXT_CLASS指定的類,也就是AnnotationConfigServletWebServerApplicationContext類,我們來用圖來說明下這個類的關(guān)系

SpringBoot中怎么啟動Tomcat

通過這個類圖我們可以知道,這個類繼承的是ServletWebServerApplicationContext,這就是我們真正的主角,而這個類最終是繼承了AbstractApplicationContext,了解完創(chuàng)建上下文的情況后,我們再來看看刷新上下文,相關(guān)代碼如下:

SpringBoot中怎么啟動Tomcat

這里還是直接傳遞調(diào)用本類的refresh(context)方法,最后是強轉(zhuǎn)成父類AbstractApplicationContext調(diào)用其refresh()方法,該代碼如下:

// 類:AbstractApplicationContext public void refresh() throws BeansException, IllegalStateException{ synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses.這里的意思就是調(diào)用各個子類的onRefresh() onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }

這里我們看到onRefresh()方法是調(diào)用其子類的實現(xiàn),根據(jù)我們上文的分析,我們這里的子類是ServletWebServerApplicationContext。

SpringBoot中怎么啟動Tomcat

到這里,其實廬山真面目已經(jīng)出來了,createWebServer()就是啟動web服務,但是還沒有真正啟動Tomcat,既然webServer是通過ServletWebServerFactory來獲取的,我們就來看看這個工廠的真面目。

SpringBoot中怎么啟動Tomcat

走進Tomcat內(nèi)部

根據(jù)上圖我們發(fā)現(xiàn),工廠類是一個接口,各個具體服務的實現(xiàn)是由各個子類來實現(xiàn)的,所以我們就去看看TomcatServletWebServerFactory.getWebServer()的實現(xiàn)。

SpringBoot中怎么啟動Tomcat

根據(jù)上面的代碼,我們發(fā)現(xiàn)其主要做了兩件事情,第一件事就是把Connnctor(我們稱之為連接器)對象添加到Tomcat中,第二件事就是configureEngine,這連接器我們勉強能理解(不理解后面會述說),那這個Engine是什么呢?我們查看tomcat.getEngine()的源碼:

SpringBoot中怎么啟動Tomcat

根據(jù)上面的源碼,我們發(fā)現(xiàn),原來這個Engine是容器,我們繼續(xù)跟蹤源碼,找到Container接口

SpringBoot中怎么啟動Tomcat

上圖中,我們看到了4個子接口,分別是Engine,Host,Context,Wrapper。我們從繼承關(guān)系上可以知道他們都是容器,那么他們到底有啥區(qū)別呢?我看看他們的注釋是怎么說的。

/** If used, an Engine is always the top level Container in a Catalina * hierarchy. Therefore, the implementation's <code>setParent()</code> method * should throw <code>IllegalArgumentException</code>. * * @author Craig R. McClanahan */publicinterface Engine extends Container{    //省略代碼}/** * <p> * 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. * </p><p> * The child containers attached to a Host are generally implementations * of Context (representing an individual servlet context). * * @author Craig R. McClanahan */publicinterface Host extends Container{//省略代碼    }/*** </p><p> * 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. * </p><p> * The child containers attached to a Context are generally implementations * of Wrapper (representing individual servlet definitions). * </p><p> * * @author Craig R. McClanahan */publicinterface Context extends Container, ContextBind{    //省略代碼}/**</p><p> * 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. * </p><p> * Child Containers are not allowed on Wrapper implementations, so the * <code>addChild()</code> method should throw an * <code>IllegalArgumentException</code>. * * @author Craig R. McClanahan */publicinterface Wrapper extends Container{    //省略代碼}


上面的注釋翻譯過來就是,Engine是最高級別的容器,其子容器是Host,Host的子容器是Context,WrapperContext的子容器,所以這4個容器的關(guān)系就是父子關(guān)系,也就是Engine>Host>Context>Wrapper。 我們再看看Tomcat類的源碼:

//部分源碼,其余部分省略。public class Tomcat {//設(shè)置連接器
     public void setConnector(Connector connector) {
        Service service = getService();        boolean found = false;        for (Connector serviceConnector : service.findConnectors()) {            if (connector == serviceConnector) {
                found = true;
            }
        }        if (!found) {
            service.addConnector(connector);
        }
    }    //獲取service
       public Service getService() {        return getServer().findServices()[0];
    }    //設(shè)置Host容器
     public void setHost(Host host) {
        Engine engine = getEngine();        boolean found = false;        for (Container engineHost : engine.findChildren()) {            if (engineHost == host) {
                found = true;
            }
        }        if (!found) {
            engine.addChild(host);
        }
    }    //獲取Engine容器
     public Engine getEngine() {
        Service service = getServer().findServices()[0];        if (service.getContainer() != null) {            return service.getContainer();
        }
        Engine engine = new StandardEngine();
        engine.setName( "Tomcat" );
        engine.setDefaultHost(hostname);
        engine.setRealm(createDefaultRealm());
        service.setContainer(engine);        return engine;
    }    //獲取server
       public Server getServer() {        if (server != null) {            return server;
        }

        System.setProperty("catalina.useNaming", "false");

        server = new StandardServer();

        initBaseDir();        // Set configuration source
        ConfigFileLoader.setSource(new CatalinaBaseConfigurationSource(new File(basedir), null));

        server.setPort( -1 );

        Service service = new StandardService();
        service.setName("Tomcat");
        server.addService(service);        return server;
    }    
    //添加Context容器
      public Context addContext(Host host, String contextPath, String contextName,
            String dir) {
        silence(host, contextName);
        Context ctx = createContext(host, contextPath);
        ctx.setName(contextName);
        ctx.setPath(contextPath);
        ctx.setDocBase(dir);
        ctx.addLifecycleListener(new FixContextListener());        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }        
    //添加Wrapper容器
         public static Wrapper addServlet(Context ctx,
                                      String servletName,
                                      Servlet servlet) {        // will do class for name and set init params
        Wrapper sw = new ExistingStandardWrapper(servlet);
        sw.setName(servletName);
        ctx.addChild(sw);        return sw;
    }
    
}

閱讀TomcatgetServer()我們可以知道,Tomcat的最頂層是Server,Server就是Tomcat的實例,一個Tomcat一個Server;通過getEngine()我們可以了解到Server下面是Service,而且是多個,一個Service代表我們部署的一個應用,而且我們還可以知道,Engine容器,一個service只有一個;根據(jù)父子關(guān)系,我們看setHost()源碼可以知道,host容器有多個;同理,我們發(fā)現(xiàn)addContext()源碼下,Context也是多個;addServlet()表明Wrapper容器也是多個,而且這段代碼也暗示了,其實WrapperServlet是一層意思。另外我們根據(jù)setConnector源碼可以知道,連接器(Connector)是設(shè)置在service下的,而且是可以設(shè)置多個連接器(Connector)。

根據(jù)上面分析,我們可以小結(jié)下: Tomcat主要包含了2個核心組件,連接器(Connector)和容器(Container),用圖表示如下:

SpringBoot中怎么啟動Tomcat

一個Tomcat是一個Server,一個Server下有多個service,也就是我們部署的多個應用,一個應用下有多個連接器(Connector)和一個容器(Container),容器下有多個子容器,關(guān)系用圖表示如下:

SpringBoot中怎么啟動Tomcat

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

總結(jié)

SpringBoot的啟動是通過new SpringApplication()實例來啟動的,啟動過程主要做如下幾件事情: > 1. 配置屬性 > 2. 獲取監(jiān)聽器,發(fā)布應用開始啟動事件 > 3. 初始化輸入?yún)?shù) > 4. 配置環(huán)境,輸出banner > 5. 創(chuàng)建上下文 > 6. 預處理上下文 > 7. 刷新上下文 > 8. 再刷新上下文 > 9. 發(fā)布應用已經(jīng)啟動事件 > 10. 發(fā)布應用啟動完成事件

而啟動Tomcat就是在第7步中“刷新上下文”;Tomcat的啟動主要是初始化2個核心組件,連接器(Connector)和容器(Container),一個Tomcat實例就是一個Server,一個Server包含多個Service,也就是多個應用程序,每個Service包含多個連接器(Connetor)和一個容器(Container),而容器下又有多個子容器,按照父子關(guān)系分別為:Engine,Host,Context,Wrapper,其中除了Engine外,其余的容器都是可以有多個。

分享文章:SpringBoot中怎么啟動Tomcat
地址分享:http://bm7419.com/article26/igodjg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設(shè)計公司靜態(tài)網(wǎng)站、關(guān)鍵詞優(yōu)化、虛擬主機、網(wǎng)站設(shè)計公司、外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應式網(wǎng)站建設(shè)