源码分析之Spring MVC上下文的加载细节(一)

题记:
为了解SpringMVC加载过程的细节,最近阅读了其部分源码,并自己手写实现了一个简单的SpringMVC框架,现记录作为总结。

分为三篇博客:
• 源码分析之Spring MVC上下文的加载细节(一)【本篇】
源码分析之Spring MVC上下文的加载细节(二)
源码分析之动手实现手写一个自己的SpringMVC框架(三)

阅读完这三篇博客,将了解到:
• Spring容器整套技术是如何与我们web容器的耦合?
• Spring MVC启动自己持有的MVC上下文之前需要IOC容器的支持,Spring是如何驱动IOC容器的初始化的细节的?
• Spring MVC上下文初始化以及组件和服务初始化细节?
• 完成一个属于的自己SpringMVC框架

1.整体过程

《源码分析之Spring MVC上下文的加载细节(一)》

2.Spring容器整套技术是如何与我们web容器的耦合?

首先来看Spring容器在web.xml文件中的加载顺序:
《源码分析之Spring MVC上下文的加载细节(一)》
接着我们来看ContextLoaderListener的源码:
《源码分析之Spring MVC上下文的加载细节(一)》
《源码分析之Spring MVC上下文的加载细节(一)》
小结:
从源码中可发现,ContextLoaderListener中监听整个Spring容器的初始化和销毁,ContextLoaderListener是Spring容器提供的监听器,它实现了ServletContextListener,规范了Spring IoC容器的生命周期的回调,实际上它交由其父类ContextLoader完成IoC容器初始化细节。
现在我们查看ContextLoader.initWebApplicationContext方法的源码来了解它如何驱动初始化IoC容器细节。

3.Spring如何驱动IOC容器的初始化细节

(1).ContextLoader.initWebApplicationContext方法源码分析(注意代码注释):

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    // ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE:Spring当中指定存储我们根上下文(即ServletContext/WebApplicationContext)的位置
    // 根上下文必须唯一,通过ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE看是否拿到上下文
    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.
        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) {
                    // 设置父上下文 设置应用程序id,Spring的WebApplicationContext实际是Servlet的ServletContext的延续
                    // 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);
                }
                // 装配和刷新WebApplicationContext容器,这里是一个关键点
                configureAndRefreshWebApplicationContext(cwac, servletContext);
            }
        }
        // 这里对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.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");
        }
        // 至此,返回初始化好的WebApplicationContext,对SpringMVC或Struts是一个强大支持
        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;
    }
}

(2)IOC容器初始化进一步细节,我们来查看刚刚源码initWebApplicationContext中说到的关键点,也就是configureAndRefreshWebApplicationContext方法

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
        // 获取ServletContext 上下文CONTEXT_ID_PARAM
        // 根据配置设置更合适的CONTEXT_ID_PARAM
        String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
        if (idParam != null) {
            wac.setId(idParam);
        }
        else {
            // Generate default id...
            // null时使用Spring设置默认的id
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                    ObjectUtils.getDisplayString(sc.getContextPath()));
        }
    }
    // 设置ServletContext,建立一种继承关系
    // 这里sc(ServletContext)是web容器(tomcat)或者说Servlet容器的根上下文,为IoC容器提供一个宿主环境
    wac.setServletContext(sc);
    // 获取到外部配置路径的参数
    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) {
        // 确保Servlet的属性初始化就位
        ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
    }
    // 选择什么类型的IOC容器初始化
    customizeContext(sc, wac);
    // IOC容器初始化的一个启动节点,各个工厂开始慢慢运行。。。
    wac.refresh();
}

至此,解析了整体图中的路线1——初始化通用上下文,下一篇文章是关于路线2——初始化Spring MVC上下文

    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/honhong1024/article/details/79531276
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞