欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot中如何啟動Tomcat流程

 更新時間:2019年05月10日 12:04:50   作者:胡一省  
這篇文章主要介紹了SpringBoot中如何啟動Tomcat流程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

前面在一篇文章中介紹了 Spring 中的一些重要的 context。有一些在此文中提到的 context,可以參看上篇文章。

SpringBoot 項(xiàng)目之所以部署簡單,其很大一部分原因就是因?yàn)椴挥米约赫垓v Tomcat 相關(guān)配置,因?yàn)槠浔旧韮?nèi)置了各種 Servlet 容器。一直好奇: SpringBoot 是怎么通過簡單運(yùn)行一個 main 函數(shù),就能將容器啟動起來,并將自身部署到其上 。此文想梳理清楚這個問題。

我們從SpringBoot的啟動入口中分析:

Context 創(chuàng)建

// Create, load, refresh and run the ApplicationContext
context = createApplicationContext();

在SpringBoot 的 run 方法中,我們發(fā)現(xiàn)其中很重要的一步就是上面的一行代碼。注釋也寫的很清楚:

創(chuàng)建、加載、刷新、運(yùn)行 ApplicationContext。

繼續(xù)往里面走。

protected ConfigurableApplicationContext createApplicationContext() {
  Class<?> contextClass = this.applicationContextClass;
  if (contextClass == null) {
    try {
     contextClass = Class.forName(this.webEnvironment
        ? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
    }
    catch (ClassNotFoundException ex) {
     throw new IllegalStateException(
        "Unable create a default ApplicationContext, "
           + "please specify an ApplicationContextClass",
        ex);
   }
  }
  return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
}
 

邏輯很清楚:

先找到 context 類,然后利用工具方法將其實(shí)例化。

其中 第5行 有個判斷:如果是 web 環(huán)境,則加載 DEFAULT _WEB_CONTEXT_CLASS類。參看成員變量定義,其類名為:

AnnotationConfigEmbeddedWebApplicationContext

此類的繼承結(jié)構(gòu)如圖:

直接繼承 GenericWebApplicationContext。關(guān)于該類前文已有介紹,只要記得它是專門為 web application提供context 的就好。

refresh

在經(jīng)歷過 Context 的創(chuàng)建以及Context的一些列初始化之后,調(diào)用 Context 的 refresh 方法,真正的好戲才開始上演。

從前面我們可以看到AnnotationConfigEmbeddedWebApplicationContext的繼承結(jié)構(gòu),調(diào)用該類的refresh方法,最終會由其直接父類:EmbeddedWebApplicationContext 來執(zhí)行。

@Override
 protected void onRefresh() {
  super.onRefresh();
  try {
    createEmbeddedServletContainer();
  }
  catch (Throwable ex) {
    throw new ApplicationContextException("Unable to start embedded container",
       ex);
  }
}

我們重點(diǎn)看第5行。

private void createEmbeddedServletContainer() {
  EmbeddedServletContainer localContainer = this.embeddedServletContainer;
  ServletContext localServletContext = getServletContext();
  if (localContainer == null && localServletContext == null) {
    EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
    this.embeddedServletContainer = containerFactory
       .getEmbeddedServletContainer(getSelfInitializer());
  }
  else if (localServletContext != null) {
   try {
     getSelfInitializer().onStartup(localServletContext);
   }
   catch (ServletException ex) {
     throw new ApplicationContextException("Cannot initialize servlet context",
        ex);
   }
  }
  initPropertySources();
}

代碼第5行,獲取到了一個EmbeddedServletContainerFactory,顧名思義,其作用就是為了下一步創(chuàng)建一個嵌入式的 servlet 容器:EmbeddedServletContainer。

public interface EmbeddedServletContainerFactory {
 
  /**
   * 創(chuàng)建一個配置完全的但是目前還處于“pause”狀態(tài)的實(shí)例.
   * 只有其 start 方法被調(diào)用后,Client 才能與其建立連接。
   */
  EmbeddedServletContainer getEmbeddedServletContainer(
     ServletContextInitializer... initializers);
 
}

第6、7行,在 containerFactory 獲取EmbeddedServletContainer的時候,參數(shù)為 getSelfInitializer 函數(shù)的執(zhí)行結(jié)果。暫時不管其內(nèi)部機(jī)制如何,只要知道它會返回一個 ServletContextInitializer 用于容器初始化的對象即可,我們繼續(xù)往下看。

由于 EmbeddedServletContainerFactory 是個抽象工廠,不同的容器有不同的實(shí)現(xiàn),因?yàn)镾pringBoot默認(rèn)使用Tomcat,所以就以 Tomcat 的工廠實(shí)現(xiàn)類 TomcatEmbeddedServletContainerFactory 進(jìn)行分析:

 @Override
 public EmbeddedServletContainer getEmbeddedServletContainer(
    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);
  tomcat.getEngine().setBackgroundProcessorDelay(-);
  for (Connector additionalConnector : this.additionalTomcatConnectors) {
   tomcat.getService().addConnector(additionalConnector);
  }
  prepareContext(tomcat.getHost(), initializers);
  return getTomcatEmbeddedServletContainer(tomcat);
}

從第8行一直到第16行完成了 tomcat 的 connector 的添加。tomcat 中的 connector 主要負(fù)責(zé)用來處理 http 請求,具體原理可以參看 Tomcat 的源碼,此處暫且不提。

第17行的 方法有點(diǎn)長,重點(diǎn)看其中的幾行:

 if (isRegisterDefaultServlet()) {
  addDefaultServlet(context);
 }
 if (isRegisterJspServlet() && ClassUtils.isPresent(getJspServletClassName(),
    getClass().getClassLoader())) {
  addJspServlet(context);
  addJasperInitializer(context);
  context.addLifecycleListener(new StoreMergedWebXmlListener());
 }
ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
configureContext(context, initializersToUse);

前面兩個分支判斷添加了默認(rèn)的 servlet類和與 jsp 相關(guān)的 servlet 類。

對所有的 ServletContextInitializer 進(jìn)行合并后,利用合并后的初始化類對 context 進(jìn)行配置。

第 18 行,順著方法一直往下走,開始正式啟動 Tomcat。

private synchronized void initialize() throws EmbeddedServletContainerException {
  TomcatEmbeddedServletContainer.logger
     .info("Tomcat initialized with port(s): " + getPortsDescription(false));
  try {
    addInstanceIdToEngineName();
 
    // Remove service connectors to that protocol binding doesn't happen yet
    removeServiceConnectors();
 
   // Start the server to trigger initialization listeners
   this.tomcat.start();

   // We can re-throw failure exception directly in the main thread
   rethrowDeferredStartupExceptions();

   // Unlike Jetty, all Tomcat threads are daemon threads. We create a
   // blocking non-daemon to stop immediate shutdown
   startDaemonAwaitThread();
  }
  catch (Exception ex) {
   throw new EmbeddedServletContainerException("Unable to start embedded Tomcat",
      ex);
  }
}

第11行正式啟動 tomcat。

現(xiàn)在我們回過來看看之前的那個 getSelfInitializer 方法:

private ServletContextInitializer getSelfInitializer() {
  return new ServletContextInitializer() {
   @Override
   public void onStartup(ServletContext servletContext) throws ServletException {
     selfInitialize(servletContext);
   }
  };
}
private void selfInitialize(ServletContext servletContext) throws ServletException {
  prepareEmbeddedWebApplicationContext(servletContext);
  ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes(
     beanFactory);
  WebApplicationContextUtils.registerWebApplicationScopes(beanFactory,
     getServletContext());
  existingScopes.restore();
  WebApplicationContextUtils.registerEnvironmentBeans(beanFactory,
     getServletContext());
  for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
   beans.onStartup(servletContext);
  }
}

在第2行的prepareEmbeddedWebApplicationContext方法中主要是將 EmbeddedWebApplicationContext 設(shè)置為rootContext。

第4行允許用戶存儲自定義的 scope。

第6行主要是用來將web專用的scope注冊到BeanFactory中,比如("request", "session", "globalSession", "application")。

第9行注冊web專用的environment bean(比如 ("contextParameters", "contextAttributes"))到給定的 BeanFactory 中。

第11和12行,比較重要,主要用來配置 servlet、filters、listeners、context-param和一些初始化時的必要屬性。

以其一個實(shí)現(xiàn)類ServletContextInitializer試舉一例:

@Override
 public void onStartup(ServletContext servletContext) throws ServletException {
  Assert.notNull(this.servlet, "Servlet must not be null");
  String name = getServletName();
  if (!isEnabled()) {
    logger.info("Servlet " + name + " was not registered (disabled)");
    return;
  }
  logger.info("Mapping servlet: '" + name + "' to " + this.urlMappings);
  Dynamic added = servletContext.addServlet(name, this.servlet);
  if (added == null) {
   logger.info("Servlet " + name + " was not registered "
      + "(possibly already registered?)");
   return;
  }
  configure(added);
}

可以看第9行的打?。?正是在這里實(shí)現(xiàn)了 servlet 到 URLMapping的映射。

總結(jié)

這篇文章從主干脈絡(luò)分析找到了為什么在SpringBoot中不用自己配置Tomcat,內(nèi)置的容器是怎么啟動起來的,順便在分析的過程中找到了我們常用的 urlMapping 映射 Servlet 的實(shí)現(xiàn)。

相關(guān)文章

  • 淺談Java內(nèi)省機(jī)制

    淺談Java內(nèi)省機(jī)制

    本文主要介紹了Java內(nèi)省機(jī)制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • mybatis中#{}和${}的區(qū)別詳解

    mybatis中#{}和${}的區(qū)別詳解

    本文主要介紹了mybatis中#{}和${}的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • Java拋出異常與自定義異常類應(yīng)用示例

    Java拋出異常與自定義異常類應(yīng)用示例

    這篇文章主要介紹了Java拋出異常與自定義異常類,結(jié)合實(shí)例形式分析了Java針對錯誤與異常處理的try、catch、throw等語句相關(guān)使用技巧,需要的朋友可以參考下
    2019-03-03
  • Java流程控制語句之If選擇結(jié)構(gòu)

    Java流程控制語句之If選擇結(jié)構(gòu)

    今天繼續(xù)帶大家復(fù)習(xí)Java流程控制語句的相關(guān)知識,本文對If選擇結(jié)構(gòu)作了非常詳細(xì)的介紹及代碼示例,對正在學(xué)習(xí)的小伙伴們很有幫助,需要的朋友可以參考下
    2021-06-06
  • 淺析Java Mail無法解析帶分號的收件人列表的問題

    淺析Java Mail無法解析帶分號的收件人列表的問題

    JAVA MAIL嚴(yán)格按照RFC 822規(guī)范進(jìn)行操作,沒有對分號做處理。大多數(shù)郵件服務(wù)器都是嚴(yán)格遵循RFC 822規(guī)范的
    2013-08-08
  • SpringBoot整合JWT Token的完整步驟

    SpringBoot整合JWT Token的完整步驟

    JSON Web Token是目前最流行的跨域認(rèn)證解決方案,適合前后端分離項(xiàng)目通過Restful API進(jìn)行數(shù)據(jù)交互時進(jìn)行身份認(rèn)證,這篇文章主要給大家介紹了關(guān)于SpringBoot整合JWT Token的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • Java NIO 文件通道 FileChannel 用法及原理

    Java NIO 文件通道 FileChannel 用法及原理

    這篇文章主要介紹了Java NIO 文件通道 FileChannel 用法和原理,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-01-01
  • 詳解SpringBoot程序啟動時執(zhí)行初始化代碼

    詳解SpringBoot程序啟動時執(zhí)行初始化代碼

    這篇文章主要介紹了詳解SpringBoot程序啟動時執(zhí)行初始化代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-09-09
  • IDEA 2020.1 搜索不到Chinese ​(Simplified)​ Language Pack EAP,無法安裝的問題

    IDEA 2020.1 搜索不到Chinese ​(Simplified)​ Language

    小編在安裝中文插件時遇到IDEA 2020.1 搜索不到Chinese &#8203;(Simplified)&#8203; Language Pack EAP,無法安裝的問題,本文給大家分享我的解決方法,感興趣的朋友一起看看吧
    2020-04-04
  • Spring Boot線程池使用的一些實(shí)用心得

    Spring Boot線程池使用的一些實(shí)用心得

    理論上線程越多程序可能更快,但在實(shí)際使用中我們需要考慮到線程本身的創(chuàng)建以及銷毀的資源消耗,以及保護(hù)操作系統(tǒng)本身的目的我們通常需要將線程限制在一定的范圍之類,這篇文章主要給大家介紹了關(guān)于Spring Boot線程池使用的一些實(shí)用心得,需要的朋友可以參考下
    2021-09-09

最新評論