自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Tomcat在SpringBoot中是如何啟動的

開發(fā) 后端
本文將以Tomcat為例,來看看SpringBoot是如何啟動Tomcat的,同時也將展開學習下Tomcat的源碼,了解Tomcat的設計。

 [[273866]]

前言

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

從 Main 方法說起

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

  1. @SpringBootApplication  
  2. public class TomcatdebugApplication {  
  3.     public static void main(String[] args) {  
  4.         SpringApplication.run(TomcatdebugApplication.class, args);  
  5.     }  

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

  1. public ConfigurableApplicationContext run(String... args) {  
  2.         StopWatch stopWatch = new StopWatch();  
  3.         stopWatch.start();  
  4.         ConfigurableApplicationContext context = null 
  5.         Collection<springbootexceptionreporter> exceptionReporters = new ArrayList&lt;&gt;();  
  6.         //設置系統(tǒng)屬性『java.awt.headless』,為true則啟用headless模式支持  
  7.         configureHeadlessProperty();  
  8.         //通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,  
  9.        //找到聲明的所有SpringApplicationRunListener的實現(xiàn)類并將其實例化,  
  10.        //之后逐個調用其started()方法,廣播SpringBoot要開始執(zhí)行了  
  11.         SpringApplicationRunListeners listeners = getRunListeners(args);  
  12.         //發(fā)布應用開始啟動事件  
  13.         listeners.starting();  
  14.         try {  
  15.         //初始化參數(shù)  
  16.             ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);  
  17.             //創(chuàng)建并配置當前SpringBoot應用將要使用的Environment(包括配置要使用的PropertySource以及Profile),  
  18.         //并遍歷調用所有的SpringApplicationRunListener的environmentPrepared()方法,廣播Environment準備完畢。  
  19.             ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);  
  20.             configureIgnoreBeanInfo(environment);  
  21.             //打印banner  
  22.             Banner printedBanner = printBanner(environment);  
  23.             //創(chuàng)建應用上下文  
  24.             context = createApplicationContext();  
  25.             //通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,獲取并實例化異常分析器  
  26.             exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,  
  27.                     new Class[] { ConfigurableApplicationContext.class }, context);  
  28.             //為ApplicationContext加載environment,之后逐個執(zhí)行ApplicationContextInitializer的initialize()方法來進一步封裝ApplicationContext,  
  29.         //并調用所有的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一個空的contextPrepared()方法】,  
  30.         //之后初始化IoC容器,并調用SpringApplicationRunListener的contextLoaded()方法,廣播ApplicationContext的IoC加載完成,  
  31.         //這里就包括通過**@EnableAutoConfiguration**導入的各種自動配置類。  
  32.             prepareContext(context, environment, listeners, applicationArguments, printedBanner);  
  33.             //刷新上下文  
  34.             refreshContext(context);  
  35.             //再一次刷新上下文,其實是空方法,可能是為了后續(xù)擴展。  
  36.             afterRefresh(context, applicationArguments);  
  37.             stopWatch.stop();  
  38.             if (this.logStartupInfo) {  
  39.                 new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);  
  40.             }  
  41.             //發(fā)布應用已經(jīng)啟動的事件  
  42.             listeners.started(context);  
  43.             //遍歷所有注冊的ApplicationRunner和CommandLineRunner,并執(zhí)行其run()方法。  
  44.         //我們可以實現(xiàn)自己的ApplicationRunner或者CommandLineRunner,來對SpringBoot的啟動過程進行擴展。  
  45.             callRunners(context, applicationArguments);  
  46.         }  
  47.         catch (Throwable ex) {  
  48.             handleRunFailure(context, ex, exceptionReporters, listeners);  
  49.             throw new IllegalStateException(ex);  
  50.         }  
  51.         try {  
  52.         //應用已經(jīng)啟動完成的監(jiān)聽事件  
  53.             listeners.running(context);  
  54.         }  
  55.         catch (Throwable ex) {  
  56.             handleRunFailure(context, ex, exceptionReporters, null);  
  57.             throw new IllegalStateException(ex);  
  58.         }  
  59.         return context;  
  60.     } 

其實這個方法我們可以簡單的總結下步驟為 > 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內容的話,只需要關注兩個內容即可,上下文是如何創(chuàng)建的,上下文是如何刷新的,分別對應的方法就是createApplicationContext() 和refreshContext(context),接下來我們來看看這兩個方法做了什么。 

  1. protected ConfigurableApplicationContext createApplicationContext() {  
  2.         Class<!--?--> contextClass = this.applicationContextClass;  
  3.         if (contextClass == null) {  
  4.             try {  
  5.                 switch (this.webApplicationType) {  
  6.                 case SERVLET:  
  7.                     contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);  
  8.                     break;  
  9.                 case REACTIVE:  
  10.                     contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);  
  11.                     break;  
  12.                 default:  
  13.                     contextClass = Class.forName(DEFAULT_CONTEXT_CLASS); 
  14.                 }  
  15.             }  
  16.             catch (ClassNotFoundException ex) {  
  17.                 throw new IllegalStateException(  
  18.                         "Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass",  
  19.                         ex);  
  20.             }  
  21.         }  
  22.         return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);  
  23.     } 

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

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

  1. //類:SpringApplication.java  
  2. private void refreshContext(ConfigurableApplicationContext context) {  
  3.     //直接調用刷新方法  
  4.         refresh(context);  
  5.         if (this.registerShutdownHook) {  
  6.             try {  
  7.                 context.registerShutdownHook();  
  8.             }  
  9.             catch (AccessControlException ex) {  
  10.                 // Not allowed in some environments.  
  11.             }  
  12.         }  
  13.     }  
  14. //類:SpringApplication.java  
  15. protected void refresh(ApplicationContext applicationContext) {  
  16.         Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);  
  17.         ((AbstractApplicationContext) applicationContext).refresh();  
  18.     } 

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

  1. // 類:AbstractApplicationContext   
  2. public void refresh() throws BeansException, IllegalStateException {  
  3.         synchronized (this.startupShutdownMonitor) {  
  4.             // Prepare this context for refreshing.  
  5.             prepareRefresh();  
  6.             // Tell the subclass to refresh the internal bean factory.  
  7.             ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();  
  8.             // Prepare the bean factory for use in this context.  
  9.             prepareBeanFactory(beanFactory);  
  10.             try {  
  11.                 // Allows post-processing of the bean factory in context subclasses.  
  12.                 postProcessBeanFactory(beanFactory);  
  13.                 // Invoke factory processors registered as beans in the context.  
  14.                 invokeBeanFactoryPostProcessors(beanFactory);  
  15.                 // Register bean processors that intercept bean creation.  
  16.                 registerBeanPostProcessors(beanFactory);  
  17.                 // Initialize message source for this context.  
  18.                 initMessageSource();  
  19.                 // Initialize event multicaster for this context.  
  20.                 initApplicationEventMulticaster();  
  21.                 // Initialize other special beans in specific context subclasses.這里的意思就是調用各個子類的onRefresh()  
  22.                 onRefresh();  
  23.                 // Check for listener beans and register them.  
  24.                 registerListeners();  
  25.                 // Instantiate all remaining (non-lazy-init) singletons.  
  26.                 finishBeanFactoryInitialization(beanFactory);  
  27.                 // Last step: publish corresponding event.  
  28.                 finishRefresh();  
  29.             }  
  30.             catch (BeansException ex) {  
  31.                 if (logger.isWarnEnabled()) {  
  32.                     logger.warn("Exception encountered during context initialization - " +  
  33.                             "cancelling refresh attempt: " + ex);  
  34.                 }  
  35.                 // Destroy already created singletons to avoid dangling resources.  
  36.                 destroyBeans();  
  37.                 // Reset 'active' flag.  
  38.                 cancelRefresh(ex);  
  39.                 // Propagate exception to caller.  
  40.                 throw ex;  
  41.             }  
  42.             finally {  
  43.                 // Reset common introspection caches in Spring's core, since we  
  44.                 // might not ever need metadata for singleton beans anymore...  
  45.                 resetCommonCaches();  
  46.             }  
  47.         }  
  48.     } 

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

  1. //類:ServletWebServerApplicationContext  
  2. protected void onRefresh() {  
  3.         super.onRefresh();  
  4.         try {  
  5.             createWebServer();  
  6.         }  
  7.         catch (Throwable ex) {  
  8.             throw new ApplicationContextException("Unable to start web server", ex);  
  9.         }  
  10.     }   
  11. private void createWebServer() {  
  12.         WebServer webServer = this.webServer; 
  13.          ServletContext servletContext = getServletContext();  
  14.         if (webServer == null &amp;&amp; servletContext == null) {  
  15.             ServletWebServerFactory factory = getWebServerFactory();  
  16.             this.webServer = factory.getWebServer(getSelfInitializer());  
  17.         }  
  18.         else if (servletContext != null) {  
  19.             try {  
  20.                 getSelfInitializer().onStartup(servletContext); 
  21.             }  
  22.             catch (ServletException ex) {  
  23.                 throw new ApplicationContextException("Cannot initialize servlet context", ex);  
  24.             }  
  25.         }  
  26.         initPropertySources();  
  27.     } 

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

走進Tomcat內部

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

  1. @Override  
  2.     public WebServer getWebServer(ServletContextInitializer... initializers) {  
  3.         Tomcat tomcat = new Tomcat();  
  4.         File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");  
  5.         tomcat.setBaseDir(baseDir.getAbsolutePath());  
  6.         Connector connector = new Connector(this.protocol);  
  7.         tomcat.getService().addConnector(connector);  
  8.         customizeConnector(connector);  
  9.         tomcat.setConnector(connector);  
  10.         tomcat.getHost().setAutoDeploy(false);  
  11.         configureEngine(tomcat.getEngine());  
  12.         for (Connector additionalConnector : this.additionalTomcatConnectors) {  
  13.             tomcat.getService().addConnector(additionalConnector);  
  14.         }  
  15.         prepareContext(tomcat.getHost(), initializers);  
  16.         return getTomcatWebServer(tomcat);  
  17.     } 

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

  1. public Engine getEngine() {  
  2.        Service service = getServer().findServices()[0];  
  3.        if (service.getContainer() != null) {  
  4.            return service.getContainer();  
  5.        }  
  6.        Engine engine = new StandardEngine();  
  7.        engine.setName( "Tomcat" );  
  8.        engine.setDefaultHost(hostname);  
  9.        engine.setRealm(createDefaultRealm());  
  10.        service.setContainer(engine);  
  11.        return engine;  
  12.    } 

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

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

  1.  /**  
  2.  If used, an Engine is always the top level Container in a Catalina  
  3.  * hierarchy. Therefore, the implementation's <code>setParent()</code> method  
  4.  * should throw <code>IllegalArgumentException</code> 
  5.  *  
  6.  * @author Craig R. McClanahan  
  7.  */  
  8. public interface Engine extends Container {  
  9.     //省略代碼  
  10.  
  11. /**  
  12.  * <p>  
  13.  * The parent Container attached to a Host is generally an Engine, but may  
  14.  * be some other implementation, or may be omitted if it is not necessary.  
  15.  * </p><p>  
  16.  * The child containers attached to a Host are generally implementations  
  17.  * of Context (representing an individual servlet context).  
  18.  *  
  19.  * @author Craig R. McClanahan  
  20.  */  
  21. public interface Host extends Container {  
  22. //省略代碼   
  23.  
  24. /*** </p><p>  
  25.  * The parent Container attached to a Context is generally a Host, but may  
  26.  * be some other implementation, or may be omitted if it is not necessary.  
  27.  * </p><p>  
  28.  * The child containers attached to a Context are generally implementations  
  29.  * of Wrapper (representing individual servlet definitions).  
  30.  * </p><p>  
  31.  *  
  32.  * @author Craig R. McClanahan  
  33.  */  
  34. public interface Context extends Container, ContextBind {  
  35.     //省略代碼  
  36.  
  37. /**</p><p>  
  38.  * The parent Container attached to a Wrapper will generally be an  
  39.  * implementation of Context, representing the servlet context (and  
  40.  * therefore the web application) within which this servlet executes.  
  41.  * </p><p>  
  42.  * Child Containers are not allowed on Wrapper implementations, so the  
  43.  * <code>addChild()</code> method should throw an  
  44.  * <code>IllegalArgumentException</code> 
  45.  *  
  46.  * @author Craig R. McClanahan  
  47.  */  
  48. public interface Wrapper extends Container {  
  49.     //省略代碼  

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

  1. //部分源碼,其余部分省略。  
  2. public class Tomcat {  
  3. //設置連接器  
  4.      public void setConnector(Connector connector) {  
  5.         Service service = getService();  
  6.         boolean found = false 
  7.         for (Connector serviceConnector : service.findConnectors()) {  
  8.             if (connector == serviceConnector) {  
  9.                 found = true 
  10.             }  
  11.         }  
  12.         if (!found) {  
  13.             service.addConnector(connector);  
  14.         }  
  15.     }  
  16.     //獲取service  
  17.        public Service getService() {  
  18.         return getServer().findServices()[0];  
  19.     }  
  20.     //設置Host容器  
  21.      public void setHost(Host host) {  
  22.         Engine engine = getEngine();  
  23.         boolean found = false 
  24.         for (Container engineHost : engine.findChildren()) {  
  25.             if (engineHost == host) {  
  26.                 found = true 
  27.             }  
  28.         }  
  29.         if (!found) {  
  30.             engine.addChild(host);  
  31.         }  
  32.     }  
  33.     //獲取Engine容器  
  34.      public Engine getEngine() {  
  35.         Service service = getServer().findServices()[0];  
  36.         if (service.getContainer() != null) {  
  37.             return service.getContainer();  
  38.         }  
  39.         Engine engine = new StandardEngine();  
  40.         engine.setName( "Tomcat" );  
  41.         engine.setDefaultHost(hostname);  
  42.         engine.setRealm(createDefaultRealm());  
  43.         service.setContainer(engine);  
  44.         return engine;  
  45.     }  
  46.     //獲取server  
  47.        public Server getServer() {  
  48.         if (server != null) {  
  49.             return server;  
  50.         }  
  51.         System.setProperty("catalina.useNaming", "false");  
  52.         server = new StandardServer();  
  53.         initBaseDir();  
  54.         // Set configuration source  
  55.         ConfigFileLoader.setSource(new CatalinaBaseConfigurationSource(new File(basedir), null));  
  56.         server.setPort( -1 );  
  57.         Service service = new StandardService();  
  58.         service.setName("Tomcat");  
  59.         server.addService(service);  
  60.         return server;  
  61.     }     
  62.     //添加Context容器  
  63.       public Context addContext(Host host, String contextPath, String contextName,  
  64.             String dir) {  
  65.         silence(host, contextName);  
  66.         Context ctx = createContext(host, contextPath);  
  67.         ctx.setName(contextName);  
  68.         ctx.setPath(contextPath);  
  69.         ctx.setDocBase(dir);  
  70.         ctx.addLifecycleListener(new FixContextListener());  
  71.         if (host == null) {  
  72.             getHost().addChild(ctx);  
  73.         } else {  
  74.             host.addChild(ctx);  
  75.         }         
  76.     //添加Wrapper容器  
  77.          public static Wrapper addServlet(Context ctx,  
  78.                                       String servletName,  
  79.                                       Servlet servlet) {  
  80.         // will do class for name and set init params  
  81.         Wrapper sw = new ExistingStandardWrapper(servlet);  
  82.         sw.setName(servletName);  
  83.         ctx.addChild(sw);  
  84.         return sw;  
  85.     }   

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

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

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

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

總結

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),而容器下又有多個子容器,按照父子關系分別為:Engine,Host,Context,Wrapper,其中除了Engine外,其余的容器都是可以有多個。

下期展望

本期文章通過SpringBoot的啟動來窺探了Tomcat的內部結構,下一期,我們來分析下本次文章中的連接器(Connetor)和容器(Container)的作用,敬請期待。

責任編輯:龐桂玉 來源: 中國開源
相關推薦

2019-12-09 15:08:30

JavaTomcatWeb

2019-09-24 09:46:35

Tomcat連接器Lifecycle

2017-09-04 18:48:14

TomcatSpringBoot容器

2009-06-03 15:50:51

eclipse中啟動超eclipsetomcat

2017-09-04 14:40:00

LimitLatchTomcat線程

2010-06-02 13:05:52

tomcat和svn

2020-12-29 05:33:40

TomcatSpringBoot代碼

2025-02-19 10:18:29

2024-09-06 17:55:27

Springboot開發(fā)

2024-12-17 16:26:31

2009-06-05 14:59:31

Eclipse中配置T

2022-04-10 23:42:33

MySQLSQL數(shù)據(jù)庫

2017-10-27 07:11:38

TomcatUPDOWN

2020-04-28 22:58:33

Tomcat架構Service

2022-07-12 07:33:47

ES類似連表查詢

2020-12-09 09:33:16

編程語言C語言匯編語言

2018-07-17 14:25:02

SQL解析美團點評MySQL

2020-07-27 16:10:49

SpringBoottomcaJava

2018-05-21 08:52:15

Linux應用程序啟動時間

2016-08-03 17:23:47

javascripthtml前端
點贊
收藏

51CTO技術棧公眾號