SpringMVC源码分析二

在上一节中我们写到DispatcherServlet初始化过程[init()]中的最后一个步骤 initServletBean ,这个步骤比较重要我们重点分析一下。

@Override
    protected final void initServletBean() throws ServletException {
        // 记录日志 org.apache.catalina.core.ApplicationContext.log Initializing Spring DispatcherServlet 'dispatcherServlet'
        getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");

        // 记录日志
        if (logger.isInfoEnabled()) {
            // org.springframework.web.servlet.FrameworkServlet.initServletBean Initializing Servlet 'dispatcherServlet'
            logger.info("Initializing Servlet '" + getServletName() + "'");
        }

        // 记录容器启动的开始时间
        long startTime = System.currentTimeMillis();

        try {
            // 因为我们这是一个web应用,所以需要初始化webApplicationContext容器
            this.webApplicationContext = initWebApplicationContext();

            initFrameworkServlet();
        }
        catch (ServletException | RuntimeException ex) {
            logger.error("Context initialization failed", ex);
            throw ex;
        }

        if (logger.isDebugEnabled()) {
            String value = this.enableLoggingRequestDetails ?
                    "shown which may lead to unsafe logging of potentially sensitive data" :
                    "masked to prevent unsafe logging of potentially sensitive data";
            logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
                    "': request parameters and headers will be " + value);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

观察上面代码,很容易发现最重要的方法应该为 initWebApplicationContext()

protected WebApplicationContext initWebApplicationContext() {

        // 获取webApplicationContext对象,因为第一次由于spring容器还没有初始化,所以现在是获取不到的
        WebApplicationContext rootContext =
                WebApplicationContextUtils.getWebApplicationContext(getServletContext());

        WebApplicationContext wac = null;

        // 第一次时尚未初始化,所以为null。会走else
        if (this.webApplicationContext != null) {

            // A context instance was injected at construction time -> use it
            wac = this.webApplicationContext;
            if (wac instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
                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 -> set
                        // the root application context (if any; may be null) as the parent
                        cwac.setParent(rootContext);
                    }
                    configureAndRefreshWebApplicationContext(cwac);
                }
            }
        }

        if (wac == null) {

            // 换另外一种方式获取webApplicationContext: 根据 contextAttribute 进行获取。第一次同样为null
            // No context instance was injected at construction time -> see if one
            // has been registered in the servlet context. If one exists, it is assumed
            // that the parent context (if any) has already been set and that the
            // user has performed any initialization such as setting the context id
            wac = findWebApplicationContext();
        }
        if (wac == null) {
            // 创建 webApplicationContext
            // No context instance is defined for this servlet -> create a local one
            wac = createWebApplicationContext(rootContext);
        }

        if (!this.refreshEventReceived) {
            // Either the context is not a ConfigurableApplicationContext with refresh
            // support or the context injected at construction time had already been
            // refreshed -> trigger initial onRefresh manually here.
            synchronized (this.onRefreshMonitor) {
                onRefresh(wac);
            }
        }

        if (this.publishContext) {
            // Publish the context as a servlet context attribute.
            String attrName = getServletContextAttributeName();
            getServletContext().setAttribute(attrName, wac);
        }

        return wac;
    }

首先SpringMVC会通过两种方式去获取 webApplicationContext对象:(1)通过ServletContext 和 contextAttribute 去获取,首次启动的时候因为没有创建,所以两种方式都不能成功获取,则调用createWebApplicationContext(rootContext)

protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {

        Class<?> contextClass = getContextClass();  // XmlWebApplicationContext.class;

        // 判断XmlWebApplicationContext 是不是ConfigurableWebApplicationContext 的子类
        if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
            throw new ApplicationContextException(
                    "Fatal initialization error in servlet with name '" + getServletName() +
                    "': custom WebApplicationContext class [" + contextClass.getName() +
                    "] is not of type ConfigurableWebApplicationContext");
        }

        // 通过构造器反射创建一个对象
        ConfigurableWebApplicationContext wac =
                (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

        // 给XmlWebApplicationContext容器对象设置环境对象
        wac.setEnvironment(getEnvironment());
        // 设置父容器
        wac.setParent(parent);
        // 获取config文件地址信息
        String configLocation = getContextConfigLocation();
        if (configLocation != null) {
            // 给XmlWebApplicationContext容器对象设置config文件
            wac.setConfigLocation(configLocation);
        }
        // 配置和刷新XmlWebApplicationContext容器对象
        configureAndRefreshWebApplicationContext(wac);

        return wac;
    }

流程梳理:
第一步: 判断XmlWebApplicationContext(成员变量可能会替换) 是不是ConfigurableWebApplicationContext 的子类,如果不是则抛出异常
第二步:通过构造器反射创建一个XmlWebApplicationContext对象
第三步:给XmlWebApplicationContext容器对象设置环境对象和父容器信息
第四步:把获取到的配置文件位置设置到XmlWebApplicationContext对象的父类AbstractRefreshableConfigApplicationContext的configLocations属性中
第五步:配置和刷新XmlWebApplicationContext容器对象

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
        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
            if (this.contextId != null) {
                wac.setId(this.contextId);
            }
            else {
                // Generate default id...
                // 给xmlWebApplicationContext 设置一个id
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                        ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
            }
        }

        // 给xmlWebApplicationContext 设置ServletContext
        wac.setServletContext(getServletContext());
        // 给xmlWebApplicationContext 设置ServletConfig
        wac.setServletConfig(getServletConfig());
        // 给xmlWebApplicationContext 设置名命空间 DispatcherServlet-servlet
        wac.setNamespace(getNamespace());
        // 设置应用监听
        wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

        // 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(getServletContext(), getServletConfig());
        }

        // Spring 未作处理
        postProcessWebApplicationContext(wac);

        // contextInitializers.size() 为0,未做什么功能
        applyInitializers(wac);

        // TODO 容器刷新
        wac.refresh();
    }

以上代码主要是对xmlWebApplicationContext做出一些配置,主要方法应该未refresh(),refresh()为创建容器对象的关键方法,在spring ioc中也调用了该方法,我们以后分析。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容