spring源碼解析上下文初始化ContextLoaderListener

 

前言web

本文轉自「天河聊技術」微信公衆號spring

從本篇文章開始主要介紹spring源碼解析相關的spring上下文初始化、bean定義解析、beanFactory建立、初始化、bean定義註冊到beanFactory、bean實例化、依賴注入流程中相關的步驟,因爲spring源碼體系比較龐大,本次主要是跟着程序加載順序整理,遇到相關關鍵知識點會單獨出來一篇文章,之道這個整個鏈路順序解析完畢,後面spring源碼合集整理的時候會按照模塊進行歸類梳理。微信

 

 

正文app

本次主要從ContextLoaderListener這個入口進行跟蹤源碼,進行spring的源碼解析。ide

 

先簡單看下主要的類圖post

1 bean定義解析相關this

2 spring上下文相關spa

3 beanProcessor相關debug

beanProcessors對bean的過程管理抽象。orm

 

3spring容器加載

跟蹤這個方法

org.springframework.web.context.ContextLoaderListener#contextInitialized

servlet監聽器初始時會加載初始化web應用程序上下文這個方法

@Override
public void contextInitialized(ServletContextEvent event) {
   initWebApplicationContext(event.getServletContext());
}

 

跟蹤這個方法

org.springframework.web.context.ContextLoader#initWebApplicationContext

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//    web上下文是放在servlet上下文中的
      if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
         throw new IllegalStateException(
               "Cannot initialize context because there is already a root application context present - " +
               "check whether you have multiple ContextLoader* definitions in your web.xml!");
      }

      Log logger = LogFactory.getLog(ContextLoader.class);
      servletContext.log("Initializing Spring root WebApplicationContext");
      if (logger.isInfoEnabled()) {
         logger.info("Root WebApplicationContext: initialization started");
      }
      long startTime = System.currentTimeMillis();

      try {
         // Store context in local instance variable, to guarantee that
         // it is available on ServletContext shutdown.
//       初始化web程序上下文
         if (this.context == null) {
            this.context = createWebApplicationContext(servletContext);
         }
         if (this.context instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
            if (!cwac.isActive()) {
               // The context has not yet been refreshed -> provide services such as
               // setting the parent context, setting the application context id, etc
               if (cwac.getParent() == null) {
                  // The context instance was injected without an explicit parent ->
                  // determine parent for root web application context, if any.
                  ApplicationContext parent = loadParentContext(servletContext);
//                設置上下文的父類
                  cwac.setParent(parent);
               }
//             配置裝載和刷新web上下文
               configureAndRefreshWebApplicationContext(cwac, servletContext);
            }
         }
         servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

         ClassLoader ccl = Thread.currentThread().getContextClassLoader();
         if (ccl == ContextLoader.class.getClassLoader()) {
            currentContext = this.context;
         }
         else if (ccl != null) {
            currentContextPerThread.put(ccl, this.context);
         }

         if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
                  WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
         }
         if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
         }

         return this.context;
      }
      catch (RuntimeException ex) {
         logger.error("Context initialization failed", ex);
         servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
         throw ex;
      }
      catch (Error err) {
         logger.error("Context initialization failed", err);
         servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
         throw err;
      }
   }

從這裏能夠看出web上下文是存儲在servlet上下文中的,key值是

webApplicationContext.ROOT。

 

開始初始化web程序上下文

if (this.context == null) {
   this.context = createWebApplicationContext(servletContext);
}

 

跟蹤這個方法

org.springframework.web.context.ContextLoader#createWebApplicationContext

 

建立web應用上下文

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
      Class<?> contextClass = determineContextClass(sc);
//    若是上下文的類型和ConfigurableWebApplicationContext類型不一致
      if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
         throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
               "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
      }
//    返回配置上下文對象
      return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
   }

 

返回到這個方法

org.springframework.web.context.ContextLoader#initWebApplicationContext

if (cwac.getParent() == null) {

判斷上下文是不是活動的,上下文刷新過一次,尚未關閉。

 

進入到這個方法,配置裝載和刷新web上下文

org.springframework.web.context.ContextLoader#configureAndRefreshWebApplicationContext

//  配置和刷新web上下文
   protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
      if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
         // The application context id is still set to its original default value
         // -> assign a more useful id based on available information
//       從配置中獲取上下文的id
         String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
         if (idParam != null) {
            wac.setId(idParam);
         }
         else {
            // Generate default id... 生成上下文id字符串 webApplicationContext:+servlet.getContextPath()
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                  ObjectUtils.getDisplayString(sc.getContextPath()));
         }
      }

      wac.setServletContext(sc);
//    獲取配置文件路徑 contextConfigLocation,配置文件能夠是多個的,用,換行分開,能夠用佔位符
      String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
      if (configLocationParam != null) {
         wac.setConfigLocation(configLocationParam);
      }

      // The wac environment's #initPropertySources will be called in any case when the context
      // is refreshed; do it eagerly here to ensure servlet property sources are in place for
      // use in any post-processing or initialization that occurs below prior to #refresh
      ConfigurableEnvironment env = wac.getEnvironment();
      if (env instanceof ConfigurableWebEnvironment) {
         ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
      }

//    加載子類實現的上下文
      customizeContext(sc, wac);
//    上下文刷新
      wac.refresh();
   }

獲取配置文件路徑 contextConfigLocation,配置文件能夠是多個的,用,換行分開,能夠用佔位符

String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
//     加載子類實現的上下文
      customizeContext(sc, wac);

org.springframework.web.context.ContextLoader#customizeContext 上下文初始化器找到具體要初始化的上下文類進行初始化

protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
   List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
         determineContextInitializerClasses(sc);

   for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
      Class<?> initializerContextClass =
            GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
      if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
         throw new ApplicationContextException(String.format(
               "Could not apply context initializer [%s] since its generic parameter [%s] " +
               "is not assignable from the type of application context used by this " +
               "context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
               wac.getClass().getName()));
      }
      this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
   }

   AnnotationAwareOrderComparator.sort(this.contextInitializers);
   for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
      initializer.initialize(wac);
   }
}

最後

本次介紹到這裏,以上內容僅供參考。

相關文章
相關標籤/搜索