Spring基于web.xml的启动时的处理流程

发布时间 2023-11-18 13:54:30作者: 残城碎梦

基于web.xml的Spring web应用程序少不了以下这个配置:

<!-- 监听器:启动Web容器时,自动装配ApplicationContext的配置信息,完成容器的初始化-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- springMVC的核心控制器 DispatcherServlet-->
<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 指定springmvc的配置文件-->
        <param-value>classpath*:springMVC-servlet.xml</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 指定spring初始化上下文时,需要解析并加载到容器的配置文件-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:applicationContext*.xml
    </param-value>
</context-param>

ContextLoaderListener

负责web容器启动时,初始化IOC容器,并将容器置入ServletContext中。

DispatcherServlet

负责前端请求的分发,起到控制器的做用

applicationContext-*.xml

此类配置文件对应web.xml中<context-param>标签下的contextConfigLocation的配置文件路径,作用是将其xml中配置的java-bean加载到Spring IOC容器中。

springMVC-servlet.xml

此类配置文件对应web.xml中的<servlet>标签下的contextConfigLocation的配置文件路径,作用是将其xml中配置的java-bean加载到SpringMVC IOC容器中。

此配置文件中一般配置:视图映射器、国际化、上传下载解析、controller层组件等。

ContextLoaderListener

ContextLoaderListener类的代码

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    public ContextLoaderListener() {
    }

    public ContextLoaderListener(WebApplicationContext context) {
        super(context);
    }

    public void contextInitialized(ServletContextEvent event) {
        this.initWebApplicationContext(event.getServletContext());//此处是父类ContextLoader中的方法
    }

    public void contextDestroyed(ServletContextEvent event) {
        this.closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
}

ContextLoaderListener类的继承关系

 

说一下以上几个类和接口的作用:

ContextLoader

1)首先理解两个概念:全局上下文、根上下文

  • 全局上下文:指的是整个web容器的上下文ServletContext,为Spring IOC容器提供宿主环境。
  • 根上下文:WebApplicationContext,其实际的实现类是 XmlWebApplicationContext。这个就是Spring的IoC容器

 2)该类中的initWebApplicationContext方法来初始化Spring IOC容器,并将其放入到全局上下文中

  • createWebApplicationContext方法创建WebApplicationContext根上下文
  • configureAndRefreshWebApplicationContext方法读取web.xml中配置的<context-param>中的spring*.xml配置文件,最后调用onfresh执行所有组件的创建
  • 将WebApplicationContext放入ServletContext(Java Web的全局变量)中

ContextLoaderListener类

  • 继承了ContextLoader类
  • 实现了ServletContextListener接口的contextInitialized方法contextDestroyed方法,且允许当前类配置在web.xml中可通过<listener>标签下来作为web容器启动的监听类
  • web容器启动时,会调用该类中的contextInitialized方法
  • contextInitialized方法调用了其父类ContextLoader中的initWebApplicationContext方法来初始化spring IOC容器

ServletContextListener接口

  • 继承了EventListener接口
  • 声明了contextInitialized方法contextDestroyed方法来供实现类实现
  • 容器在启动和销毁时,会给实现了servletContextListener接口的监听器发出相应的通知

EventListener接口

  • 空接口,里面什么都没有
  • 官方定义:A tagging interface that all event listener interfaces must extend.

ContextLoaderListener初始化流程

  • ServletContextListener接口
    • web容器在启动和销毁时,会向ServletContextListener的实现类发送通知
  • ContextLoaderListener类
    • 实现了ServletContextListener接口,并在web.xml中配置过后,会收到web容器请求的通知
    • 继承了ContextLoader类,会调用其父类的方法来初始化spring IOC容器
  • ContextLoader类
    • 创建WebApplicationContext根上下文
    • 读取web.xml中配置的<context-param>中的spring*.xml配置文件,最后调用onfresh执行所有组件的创建
    • 将WebApplicationContext放入ServletContext(Java Web的全局上下文)中

Spring容器的初始化

调用流程:

Tomcat服务器启动时会读取项目中web.xml中的配置项来生成ServletContext,在其中注册的ContextLoaderListener是ServletContextListener接口的实现类,它会时刻监听ServletContext的动作,包括创建和销毁,ServletContext创建的时候会触发其contextInitialized()初始化方法的执行。而Spring容器的初始化操作就在这个方法之中被触发。

/**
  * Initialize the root web application context.
  */
@Override
public void contextInitialized(ServletContextEvent event) {
    initWebApplicationContext(event.getServletContext());
}

ContextLoaderListener是启动和销毁Spring的根WebApplicationContext(web容器或者web应用上下文)的引导器,其中实现了ServletContextListener的contextInitialized容器初始化方法与contextDestoryed销毁方法,用于引导根web容器的创建和销毁。

上面方法中contextInitialized就是初始化根web容器的方法。其中调用了initWebApplicationContext方法进行Spring web容器的具体创建。

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    //SpringIOC容器的重复性创建校验
    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");
    }
    //记录Spring容器创建开始时间
    long startTime = System.currentTimeMillis();

    try {
        // Store context in local instance variable, to guarantee that
        // it is available on ServletContext shutdown.
        if (this.context == null) {
            //创建Spring容器实例
            this.context = createWebApplicationContext(servletContext);
        }
        if (this.context instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
            if (!cwac.isActive()) {
                //容器只有被刷新至少一次之后才是处于active(激活)状态
                if (cwac.getParent() == null) {
                    //此处是一个空方法,返回null,也就是不设置父级容器
                    ApplicationContext parent = loadParentContext(servletContext);
                    cwac.setParent(parent);
                }
                //重点操作:配置并刷新容器
                configureAndRefreshWebApplicationContext(cwac, servletContext);
            }
        }
        //将创建完整的Spring容器作为一条属性添加到Servlet容器中
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == ContextLoader.class.getClassLoader()) {
            //如果当前线程的类加载器是ContextLoader类的类加载器的话,也就是说如果是当前线程加载了ContextLoader类的话,则将Spring容器在ContextLoader实例中保留一份引用
            currentContext = this.context;
        }
        else if (ccl != null) {
            //添加一条ClassLoader到Springweb容器的映射
            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;
    }
}

这里十分明了的显示出了ServletContext和Spring root ApplicationContext的关系:后者只是前者的一个属性,前者包含后者。

ServletContext表示的是一整个应用,其中包括应用的所有内容,而Spring只是应用所采用的一种框架。从ServletContext的角度来看,Spring其实也算是应用的一部分,属于和我们编写的代码同级的存在,只是相对于我们编码人员来说,Spring是作为一种即存的编码架构而存在的,即我们将其看作我们编码的基础,或者看作应用的基础部件。虽然是基础部件,但也是属于应用的一部分。所以将其设置到ServletContext中,而且是作为一个单一属性存在,但是它的作用却是很大的。

源码中WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的值为:WebApplicationContext.class.getName() + ".ROOT",这个正是Spring容器在Servlet容器中的属性名。

在这段源码中主要是概述Spring容器的创建和初始化,分别由两个方法实现:createWebApplicationContext方法和configureAndRefreshWebApplicationContext方法。

首先,我们需要创建Spring容器,我们需要决定使用哪个容器实现。

源码-来自:ContextLoader

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
    //决定使用哪个容器实现
    Class<?> contextClass = determineContextClass(sc);
    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);
}
//我们在web.xml中以 <context-param> 的形式设置contextclass参数来指定使用哪个容器实现类,
//若未指定则使用默认的XmlWebApplicationContext,其实这个默认的容器实现也是预先配置在一个
//叫ContextLoader.properties文件中的
protected Class<?> determineContextClass(ServletContext servletContext) {
    //获取Servlet容器中配置的系统参数contextClass的值,如果未设置则为null
    String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
    if (contextClassName != null) {
        try {
            return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
        }
        catch (ClassNotFoundException ex) {
            throw new ApplicationContextException(
                "Failed to load custom context class [" + contextClassName + "]", ex);
        }
    }
    else {
        //获取预先配置的容器实现类
        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);
        }
    }
}

BeanUtils是Spring封装的反射实现,instantiateClass方法用于实例化指定类。

我们可以在web.xml中以 <context-param> 的形式设置contextClass参数手动决定应用使用哪种Spring容器,但是一般情况下我们都遵循Spring的默认约定,使用ContextLoader.properties中配置的org.springframework.web.context.WebApplicationContext的值来作为默认的Spring容器来创建。

源码-来自:ContextLoader.properties

# 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

可见,一般基于Spring的web服务默认使用的都是XmlWebApplicationContext作为容器实现类的。

到此位置容器实例就创建好了,下一步就是配置和刷新了。

源码-来自:ContextLoader

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
        String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
        if (idParam != null) {
            wac.setId(idParam);
        }
        else {
            // Generate default id...
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                      ObjectUtils.getDisplayString(sc.getContextPath()));
        }
    }
    //在当前Spring容器中保留对Servlet容器的引用
    wac.setServletContext(sc);
    //设置web.xml中配置的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
    //在容器刷新之前,提前进行属性资源的初始化,以备使用,将ServletContext设置为servletContextInitParams
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
    }
    //取得web.xml中配置的contextInitializerClasses和globalInitializerClasses对应的初始化器,并执行初始化操作,需自定义初始化器
    customizeContext(sc, wac);
    //刷新容器
    wac.refresh();
}

首先将ServletContext的引用置入Spring容器中,以便可以方便的访问ServletContext;然后从ServletContext中找到“contextConfigLocation”参数的值,配置是在web.xml中以<context-param>形式配置的。

在Spring中凡是以<context-param>配置的内容都会在web.xml加载的时候优先存储到ServletContext之中,我们可以将其看成ServletContext的配置参数,将参数配置到ServletContext中后,我们就能方便的获取使用了,就比如此处我们就能直接从ServletContext中获取“contextConfigLocation”的值,用于初始化Spring容器。

在Java的web开发中,尤其是使用Spring开发的情况下,基本就是一个容器对应一套配置,这套配置就是用于初始化容器的。ServletContext对应于<context-param>配置,Spring容器对应applicationContext.xml配置,这个配置属于默认的配置,如果自定义名称就需要将其配置到<context-param>中备用了,还有DispatchServlet的Spring容器对应spring-mvc.xml配置文件。

Spring容器的environment表示的是容器运行的基础环境配置,其中保存的是Profile和Properties,其initPropertySources方法是在ConfigurableWebEnvironment接口中定义的,是专门用于web应用中来执行真实属性资源与占位符资源(StubPropertySource)的替换操作的。

StubPropertySource就是一个占位用的实例,在应用上下文创建时,当实际属性资源无法及时初始化时,临时使用这个实例进行占位,等到容器刷新的时候执行替换操作。

上面源码中customizeContext方法的目的是在刷新容器之前对容器进行自定义的初始化操作,需要我们实现ApplicationContextInitializer<C extends ConfigurableApplicationContext>接口,然后将其配置到web.xml中即可生效。

源码-来自:ContextLoader

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);
    }
}
protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>
		determineContextInitializerClasses(ServletContext servletContext) {

	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes =
			new ArrayList<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>();
	//通过<context-param>属性配置globalInitializerClasses获取全局初始化类名
	String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM);
	if (globalClassNames != null) {
		for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) {
			classes.add(loadInitializerClass(className));
		}
	}
	//通过<context-param>属性配置contextInitializerClasses获取容器初始化类名
	String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM);
	if (localClassNames != null) {
		for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) {
			classes.add(loadInitializerClass(className));
		}
	}

	return classes;
}

initPropertySources操作用于配置属性资源,其实在refresh操作中也会执行该操作,这里提前执行,目的为何,暂未可知。

refresh操作是容器初始化的操作,是通用操作,而到达该点的方式确实有多种,每种就是一种Spring的开发方式。

除了此处的web开发方式,还有SpringBoot开发方式。

DispatcherServlet初始化流程

ContextLoaderListener监听器初始化完毕后,开始初始化web.xml中配置的Servlet,这里是DispatcherServlet。

DispathcerServlet存在多个父类,其继承关系的最高层是接口Servlet,该接口中存在init()方法。

在DispatcherServlet的继承关系中,其各种父类的作用:

1)HttpServletBean类

  • 把DispatchServlet封装成BeanWrapper。
  • 给BeanWrapper设置属性。
  • 调用空方法initServletBean,让子类FrameworkServlet接着干

2)FrameworkServlet类

  • 从ServletContext中获取根容器,也就是spring IOC容器
  • 将Spring IOC容器设置为spring mvc IOC容器的父容器
  • 初始化spring mvc IOC容器
  • 调用DispatcherServlet的初始化方法onRefresh(wac)

3)DispatcherServlet类

  • 执行各组件的初始化
  • 接收的参数context就是spring mvc IOC容器
@Override
protected void onRefresh(ApplicationContext context) {
    initStrategies(context);
}

/**
  * Initialize the strategy objects that this servlet uses.
  * <p>May be overridden in subclasses in order to initialize further strategy objects.
  */
protected void initStrategies(ApplicationContext context) {
    initMultipartResolver(context);            // 文件上传
    initLocaleResolver(context);               // 本地解析   
    initThemeResolver(context);                // 主题解析
    initHandlerMappings(context);              // 把request映射到具体的处理器上(负责找handler)
    initHandlerAdapters(context);              // 初始化真正调用controller的类
    initHandlerExceptionResolvers(context);    // 异常解析
    initRequestToViewNameTranslator(context);   
    initViewResolvers(context);                // 视图解析
    initFlashMapManager(context);              // 管理FlashMap,主要用于redirect 
}