咱們知道SpringBoot給咱們帶來了一個全新的開發體驗,咱們能夠直接把web程序達成jar包,直接啓動,這就得益於SpringBoot內置了容器,能夠直接啓動,本文將以Tomcat爲例,來看看SpringBoot是如何啓動Tomcat的,同時也將展開學習下Tomcat的源碼,瞭解Tomcat的設計。java
用過SpringBoot的人都知道,首先要寫一個main方法來啓動web
@SpringBootApplication public class TomcatdebugApplication { public static void main(String[] args) { SpringApplication.run(TomcatdebugApplication.class, args); } }
咱們直接點擊run方法的源碼,跟蹤下來,發下最終 的run
方法是調用ConfigurableApplicationContext
方法,源碼以下:spring
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<springbootexceptionreporter> exceptionReporters = new ArrayList<>(); //設置系統屬性『java.awt.headless』,爲true則啓用headless模式支持 configureHeadlessProperty(); //經過*SpringFactoriesLoader*檢索*META-INF/spring.factories*, //找到聲明的全部SpringApplicationRunListener的實現類並將其實例化, //以後逐個調用其started()方法,廣播SpringBoot要開始執行了 SpringApplicationRunListeners listeners = getRunListeners(args); //發佈應用開始啓動事件 listeners.starting(); try { //初始化參數 ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); //建立並配置當前SpringBoot應用將要使用的Environment(包括配置要使用的PropertySource以及Profile), //並遍歷調用全部的SpringApplicationRunListener的environmentPrepared()方法,廣播Environment準備完畢。 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); configureIgnoreBeanInfo(environment); //打印banner Banner printedBanner = printBanner(environment); //建立應用上下文 context = createApplicationContext(); //經過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,獲取並實例化異常分析器 exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); //爲ApplicationContext加載environment,以後逐個執行ApplicationContextInitializer的initialize()方法來進一步封裝ApplicationContext, //並調用全部的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一個空的contextPrepared()方法】, //以後初始化IoC容器,並調用SpringApplicationRunListener的contextLoaded()方法,廣播ApplicationContext的IoC加載完成, //這裏就包括經過**@EnableAutoConfiguration**導入的各類自動配置類。 prepareContext(context, environment, listeners, applicationArguments, printedBanner); //刷新上下文 refreshContext(context); //再一次刷新上下文,實際上是空方法,多是爲了後續擴展。 afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); } //發佈應用已經啓動的事件 listeners.started(context); //遍歷全部註冊的ApplicationRunner和CommandLineRunner,並執行其run()方法。 //咱們能夠實現本身的ApplicationRunner或者CommandLineRunner,來對SpringBoot的啓動過程進行擴展。 callRunners(context, applicationArguments); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, listeners); throw new IllegalStateException(ex); } try { //應用已經啓動完成的監聽事件 listeners.running(context); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, null); throw new IllegalStateException(ex); } return context; }
其實這個方法咱們能夠簡單的總結下步驟爲 > 1. 配置屬性 > 2. 獲取監聽器,發佈應用開始啓動事件 > 3. 初始化輸入參數 > 4. 配置環境,輸出banner > 5. 建立上下文 > 6. 預處理上下文 > 7. 刷新上下文 > 8. 再刷新上下文 > 9. 發佈應用已經啓動事件 > 10. 發佈應用啓動完成事件tomcat
其實上面這段代碼,若是隻要分析tomcat內容的話,只須要關注兩個內容便可,上下文是如何建立的,上下文是如何刷新的,分別對應的方法就是createApplicationContext()
和refreshContext(context)
,接下來咱們來看看這兩個方法作了什麼。springboot
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) { throw new IllegalStateException( "Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass", ex); } } return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass); }
這裏就是根據咱們的webApplicationType
來判斷建立哪一種類型的Servlet,代碼中分別對應着Web類型(SERVLET),響應式Web類型(REACTIVE),非Web類型(default),咱們創建的是Web類型,因此確定實例化 DEFAULT_SERVLET_WEB_CONTEXT_CLASS
指定的類,也就是AnnotationConfigServletWebServerApplicationContext
類,咱們來用圖來講明下這個類的關係app
經過這個類圖咱們能夠知道,這個類繼承的是ServletWebServerApplicationContext
,這就是咱們真正的主角,而這個類最終是繼承了AbstractApplicationContext
,瞭解完建立上下文的狀況後,咱們再來看看刷新上下文,相關代碼以下:less
//類:SpringApplication.java private void refreshContext(ConfigurableApplicationContext context) { //直接調用刷新方法 refresh(context); if (this.registerShutdownHook) { try { context.registerShutdownHook(); } catch (AccessControlException ex) { // Not allowed in some environments. } } } //類:SpringApplication.java protected void refresh(ApplicationContext applicationContext) { Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext); ((AbstractApplicationContext) applicationContext).refresh(); }
這裏仍是直接傳遞調用本類的refresh(context)
方法,最後是強轉成父類AbstractApplicationContext
調用其refresh()
方法,該代碼以下:ide
// 類: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.這裏的意思就是調用各個子類的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()
方法是調用其子類的實現,根據咱們上文的分析,咱們這裏的子類是ServletWebServerApplicationContext
。post
//類:ServletWebServerApplicationContext protected void onRefresh() { super.onRefresh(); try { createWebServer(); } catch (Throwable ex) { throw new ApplicationContextException("Unable to start web server", ex); } } private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = getServletContext(); if (webServer == null && servletContext == null) { ServletWebServerFactory factory = getWebServerFactory(); this.webServer = factory.getWebServer(getSelfInitializer()); } else if (servletContext != null) { try { getSelfInitializer().onStartup(servletContext); } catch (ServletException ex) { throw new ApplicationContextException("Cannot initialize servlet context", ex); } } initPropertySources(); }
到這裏,其實廬山真面目已經出來了,createWebServer()
就是啓動web服務,可是尚未真正啓動Tomcat,既然webServer
是經過ServletWebServerFactory
來獲取的,咱們就來看看這個工廠的真面目。學習
根據上圖咱們發現,工廠類是一個接口,各個具體服務的實現是由各個子類來實現的,因此咱們就去看看TomcatServletWebServerFactory.getWebServer()
的實現。
@Override public WebServer getWebServer(ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); }
根據上面的代碼,咱們發現其主要作了兩件事情,第一件事就是把Connnctor(咱們稱之爲鏈接器)對象添加到Tomcat中,第二件事就是configureEngine
,這鏈接器咱們勉強能理解(不理解後面會述說),那這個Engine
是什麼呢?咱們查看tomcat.getEngine()
的源碼:
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; }
根據上面的源碼,咱們發現,原來這個Engine是容器,咱們繼續跟蹤源碼,找到Container
接口
上圖中,咱們看到了4個子接口,分別是Engine,Host,Context,Wrapper。咱們從繼承關係上能夠知道他們都是容器,那麼他們到底有啥區別呢?我看看他們的註釋是怎麼說的。
/** 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 */ public interface 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 */ public interface 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 */ public interface 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 */ public interface Wrapper extends Container { //省略代碼 }
上面的註釋翻譯過來就是,Engine
是最高級別的容器,其子容器是Host
,Host
的子容器是Context
,Wrapper
是Context
的子容器,因此這4個容器的關係就是父子關係,也就是Engine
>Host
>Context
>Wrapper
。 咱們再看看Tomcat
類的源碼:
//部分源碼,其他部分省略。 public class Tomcat { //設置鏈接器 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]; } //設置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; } }
閱讀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
子容器。
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外,其他的容器都是能夠有多個。
本期文章經過SpringBoot的啓動來窺探了Tomcat的內部結構,下一期,咱們來分析下本次文章中的鏈接器(Connetor
)和容器(Container)的做用,敬請期待。