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中也调用了该方法,我们以后分析。

你可能感兴趣的:(SpringMVC源码分析二)