53--Web應(yīng)用上下文環(huán)境創(chuàng)建

1. Web應(yīng)用上下文環(huán)境創(chuàng)建簡析

通過上一節(jié)的分析,找到了SpringMVC源碼分析的入口,接下來看Web應(yīng)用上下文環(huán)境創(chuàng)建過程。打開ContextLoader類的initWebApplicationContext方法:

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    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!");
    }

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

    try {
        // 將上下文存儲在本地實例變量中,以確保它在ServletContext關(guān)閉時可用。
        // Store context in local instance variable, to guarantee that it is available on ServletContext shutdown.
        if (this.context == null) {
            // 1.創(chuàng)建web應(yīng)用上線文環(huán)境
            this.context = createWebApplicationContext(servletContext);
        }
        if (this.context instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
            // 如果當(dāng)前上下文環(huán)境未激活,那么其只能提供例如設(shè)置父上下文、設(shè)置上下文id等功能
            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);
                }
                // 2.配置并刷新當(dāng)前上下文環(huán)境
                configureAndRefreshWebApplicationContext(cwac, servletContext);
            }
        }

        // 將當(dāng)前上下文環(huán)境存儲到ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE變量中
        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.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
        }

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

該方法一共涉及兩個比較重要的點:

  • 創(chuàng)建web應(yīng)用上線文環(huán)境
  • 配置并刷新當(dāng)前上下文環(huán)境
2. 創(chuàng)建web應(yīng)用上線文環(huán)境
/**
 * 為當(dāng)前類加載器實例化根WebApplicationContext,可以是默認(rèn)上線文加載類或者自定義上線文加載類
 */
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
    // 1.確定實例化WebApplicationContext所需的類
    Class<?> contextClass = determineContextClass(sc);
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
        throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
                "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
    }
    // 2.實例化得到的WebApplicationContext類
    return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}

邏輯很簡單,得到一個類,將其實例化。我們經(jīng)常說的web應(yīng)用上下文環(huán)境,是不是比我們想象的還要簡單。。。

那么要得到或者明確哪個類呢? 繼續(xù)看代碼:

/**
 * 返回WebApplicationContext(web應(yīng)用上線文環(huán)境)實現(xiàn)類
 * 如果沒有自定義默認(rèn)返回XmlWebApplicationContext類
 *
 * 兩種方式:
 * 1。非自定義:通過ContextLoader類的靜態(tài)代碼塊加載ContextLoader.properties配置文件并解析,該配置文件中的默認(rèn)類即XmlWebApplicationContext
 * 2。自定義: 通過在web.xml文件中,配置context-param節(jié)點,并配置param-name為contextClass的自己點,如
 *      <context-param>
 *          <param-name>contextClass</param-name>
 *          <param-value>org.springframework.web.context.support.MyWebApplicationContext</param-value>
 *      </context-param>
 *
 * Return the WebApplicationContext implementation class to use, either the
 * default XmlWebApplicationContext or a custom context class if specified.
 * @param servletContext current servlet context
 * @return the WebApplicationContext implementation class to use
 * @see #CONTEXT_CLASS_PARAM
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected Class<?> determineContextClass(ServletContext servletContext) {
    String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
    // 1.自定義
    if (contextClassName != null) {
        try {
            return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
        }
        catch (ClassNotFoundException ex) {
            throw new ApplicationContextException("Failed to load custom context class [" + contextClassName + "]", ex);
        }
    }
    // 2.默認(rèn)
    else {
        // 根據(jù)靜態(tài)代碼塊的加載這里 contextClassName = XmlWebApplicationContext
        contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
        try {
            return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
        }
        catch (ClassNotFoundException ex) {
            throw new ApplicationContextException("Failed to load default context class [" + contextClassName + "]", ex);
        }
    }
}

自定義方式注釋里已經(jīng)寫的很清晰了,我們來看默認(rèn)方式,這里涉及到了一個靜態(tài)變量defaultStrategies,并在下面的靜態(tài)代碼塊中對其進(jìn)行了初始化操作:

private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";

private static final Properties defaultStrategies;

/**
 * 靜態(tài)代碼加載默認(rèn)策略,即默認(rèn)的web應(yīng)用上下文
 * DEFAULT_STRATEGIES_PATH --> ContextLoader.properties
 *
 * org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
 */
static {
    // Load default strategy implementations from properties file.
    // This is currently strictly internal and not meant to be customized by application developers.
    try {
        ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
        defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
    }
    catch (IOException ex) {
        throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
    }
}

這段代碼對ContextLoader.properties進(jìn)行了解析,那么ContextLoader.properties中存儲的內(nèi)容是什么呢?

# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

很簡單,通過上面的操作,我們就可以確定contextClassName是XmlWebApplicationContext,跟我們之前分析的ApplicationContext差不多,只是在其基礎(chǔ)上又提供了對web的支持。接下來通過BeanUtils.instantiateClass(contextClass)將其實例化即可。

3.配置并刷新當(dāng)前上下文環(huán)境
/**
 * 配置并刷新當(dāng)前web應(yīng)用上下文
 */
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
    /**
     * 1.配置應(yīng)用程序上下文id
     * 如果當(dāng)前應(yīng)用程序上下文id仍然設(shè)置為其原始默認(rèn)值,則嘗試為其設(shè)置自定義上下文id,如果有的話。
     * 在web.xml中配置
     * <context-param>
     *      <param-name>contextId</param-name>
     *      <param-value>jack-2019-01-02</param-value>
     *  </context-param>
     */
    if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
        String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
        if (idParam != null) {
            wac.setId(idParam);
        }
        // 無自定義id則為其生成默認(rèn)id
        else {
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                    ObjectUtils.getDisplayString(sc.getContextPath()));
        }
    }

    wac.setServletContext(sc);

    /**
     * 2.設(shè)置配置文件路徑,如
     * <context-param>
     *      <param-name>contextConfigLocation</param-name>
     *      <param-value>classpath:spring-context.xml</param-value>
     *  </context-param>
     */
    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
    // 3.創(chuàng)建ConfigurableEnvironment并配置初始化參數(shù)
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
    }

    // 4.自定義配置上下文環(huán)境
    customizeContext(sc, wac);

    // 5.刷新上下文環(huán)境
    wac.refresh();
}

前三個步驟比較簡單,在前面的博客中多少有些介紹,我們來看自定義配置上下文環(huán)境和刷新上下文環(huán)境

3.1 自定義配置上下文環(huán)境
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
    /**
     * 加載并實例化web.xml配置文件中的 globalInitializerClasses 和 contextInitializerClasses 配置
     *
     * globalInitializerClasses 代表所有的web application都會應(yīng)用
     * contextInitializerClasses 代表只有當(dāng)前的web application會使用
     * 例如,在web.xml配置文件中:
     *  <context-param>
     *      <param-name>contextInitializerClasses</param-name>
     *      <param-value>com.lyc.cn.init.MyContextInitializerClasses</param-value>
     *  </context-param>
     *
     *  容器將會調(diào)用自定義的initialize方法,其實就在這段代碼的下方。。。
     */
    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);
    }
}

該實現(xiàn)很簡單,我們只要在web.xml中自定義contextInitializerClasses和globalInitializerClasses并提供實現(xiàn)類即可:
如:

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.lyc.cn.init.MyContextInitializerClasses</param-value>
</context-param>
public class MyContextInitializerClasses implements ApplicationContextInitializer<XmlWebApplicationContext> {
    /**
     * Initialize the given application context.
     * @param applicationContext the application to configure
     */
    @Override
    public void initialize(XmlWebApplicationContext applicationContext) {
        System.out.println("MyContextInitializerClasses initialize ...");
        System.out.println("MyContextInitializerClasses " + applicationContext.toString());
    }
}
3.2 刷新上下文環(huán)境
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 1、準(zhǔn)備刷新上下文環(huán)境
        prepareRefresh();
        // 2、讀取xml并初始化BeanFactory
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        // 3、填充BeanFactory功能
        prepareBeanFactory(beanFactory);
        try {
            // 4、子類覆蓋方法額外處理(空方法)
            postProcessBeanFactory(beanFactory);
            // 5、調(diào)用BeanFactoryPostProcessor
            invokeBeanFactoryPostProcessors(beanFactory);
            // 6、注冊BeanPostProcessors
            registerBeanPostProcessors(beanFactory);
            // 7、初始化Message資源
            initMessageSource();
            // 8、初始事件廣播器
            initApplicationEventMulticaster();
            // 9、留給子類初始化其他Bean(空的模板方法)
            onRefresh();
            // 10、注冊事件監(jiān)聽器
            registerListeners();
            // 11、初始化其他的單例Bean(非延遲加載的)
            finishBeanFactoryInitialization(beanFactory);
            // 12、完成刷新過程,通知生命周期處理器lifecycleProcessor刷新過程,同時發(fā)出ContextRefreshEvent通知
            finishRefresh();
        }
        catch (BeansException ex) {
            // 13、銷毀已經(jīng)創(chuàng)建的Bean
            destroyBeans();
            // 14、重置容器激活標(biāo)簽
            cancelRefresh(ex);
            throw ex;
        }
        finally {
            resetCommonCaches();
        }
    }
}

這段代碼在前面的博客中已經(jīng)詳細(xì)的分析過了,感興趣的同學(xué)查看前面的博客吧! 到這里Web應(yīng)用上下文環(huán)境創(chuàng)建過程就結(jié)束了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,166評論 4 61
  • 本文是我自己在秋招復(fù)習(xí)時的讀書筆記,整理的知識點,也是為了防止忘記,尊重勞動成果,轉(zhuǎn)載注明出處哦!如果你也喜歡,那...
    波波波先森閱讀 12,442評論 6 86
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對...
    cosWriter閱讀 11,631評論 1 32
  • 改革創(chuàng)新其實是件很有意思的事情。 今天圍觀了一場三方博弈。企業(yè)以便捷為需求,希望改變規(guī)則,可惜立意太高,太過激進(jìn),...
    月之閱讀 246評論 0 0
  • 小說中,這一首的虛擬作者,70年代中期愛上一個男人,1990年終于遂愿。 圖片來自60年代日本電影《秋刀魚之味》,...
    車槐閱讀 682評論 16 7

友情鏈接更多精彩內(nèi)容