Spring Web应用的启动流程分析

在Servlet API中有一个ServletContextListener接口,它能够监听ServletContext对象的生命周期,实际上就是监听Web应用的生命周期。

当Servlet容器启动或终止Web应用时,会触发ServletContextEvent事件,该事件由ServletContextListener来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent事件的两个方法。

  • contextInitialized(ServletContextEvent sce):当Servlet容器启动Web应用时调用该方法。在调用完该方法之后,容器再对Filter初始化,并且对那些在Web应用启动时就需要被初始化的Servlet进行初始化。
  • contextDestroyed(ServletContextEvent sce):当Servlet容器终止Web应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet和Filter过滤器。

使用web.xml的启动流程分析

基于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:

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());
    }
}

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());
}

上面方法中contextInitialized就是初始化根web容器WebApplicationContext的方法。其中调用了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);
    //刷新容器, 由AbstractApplicationContext实现
    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操作是容器初始化的操作(由AbstractApplicationContext实现),是通用操作,而到达该点的方式确实有多种,每种就是一种Spring的开发方式。

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

DispatcherServlet初始化流程

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

当服务器启动的时候,如果在里面配置了<load-on-startup>的话,就会在服务器启动的时候自动加载init()方法,并且实例化servlet,但是如果没有配置,也会在DispatcherServlet第一次请求发出的时候执行DispatcherServlet的init方法,初始化SpringMVC容器。

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 
}

不使用web.xml的启动流程分析

全注解方式2个关键类

全注解的方式重点就在于2 个类:MVC初始化类、MVC 配置类

MVC初始化类

这个类需要继承 AbstractAnnotationConfigDispatcherServletInitializer,会有web容器来调用,这个类中有4个方法需要实现,干了4件事情

  • getRootConfigClasses():获取父容器的配置类
  • getServletConfigClasses():获取 springmvc 容器的配置类,这个配置类相当于 springmvc xml 配置文件的功能
  • getServletMappings():获取 DispatcherServlet 能够处理的 url,相当于 web.xml 里 servlet 指定的 url-pattern
  • getServletFilters():定义所有的 Filter

/**
 * ①:1、创建Mvc初始化类,需要继承AbstractAnnotationConfigDispatcherServletInitializer类
 */
public class MvcInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * springmvc容器的父容器spring配置类
     * 实际工作中我们的项目比较复杂,可以将controller层放在springmvc容器中
     * 其他层,如service层、dao层放在父容器了,bean管理起来更清晰一些
     * 也可以没有父容器,将所有bean都放在springmvc容器中
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    /**
     * ②:2、设置springmvc容器的spring配置类
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{MvcConfig.class};
    }

    /**
     * ③:3、配置DispatcherServlet的url-pattern
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * ④:4、注册拦截器
     *
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
        //添加拦截器,解决乱码问题
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceRequestEncoding(true);
        characterEncodingFilter.setForceResponseEncoding(true);
        return new Filter[]{characterEncodingFilter};
    }
}

MVC配置类

这个配置类相当于 springmvc xml 配置文件的功能,可以在里面定义 springmvc 各种组件。

/**
 * 1.开启springmvc注解配置
 * 2、配置视图解析器
 * 3、配置拦截器
 * 4、配置静态资源访问
 * 5、配置文件上传解析器
 * 6、配置全局异常处理器
 */
@Configuration
@ComponentScan("com.harvey.chat12")
@EnableWebMvc //1:使用EnableWebMvc开启springmvc注解方式配置
public class MvcConfig implements WebMvcConfigurer {

    /**
     * 2、添加视图解析器(可以添加多个)
     *
     * @param registry
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        resolver.setOrder(Ordered.LOWEST_PRECEDENCE);
        registry.viewResolver(resolver);
    }

    @Autowired
    private MyInterceptor myInterceptor;

    /**
     * 3、添加拦截器(可以添加多个)
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.myInterceptor).addPathPatterns("/**");
    }


    /**
     * 4、配置静态资源访问处理器
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    /**
     * 5、配置文件上传解析器
     *
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        //maxUploadSizePerFile:单个文件大小限制(byte)
        //maxUploadSize:整个请求大小限制(byte)
        commonsMultipartResolver.setMaxUploadSizePerFile(10 * 1024 * 1024);
        commonsMultipartResolver.setMaxUploadSize(100 * 1024 * 1024);
        return commonsMultipartResolver;
    }
}

Servlet3.0提供的SPI规范

从servlet3.0开始,web容器启动时为提供给第三方组件机会做一些初始化的工作,例如注册servlet或者filtes等,servlet规范中通过ServletContainerInitializer实现此功能。每个框架要使用ServletContainerInitializer就必须在对应的jar包的META-INF/services目录创建一个名为javax.servlet.ServletContainerInitializer的文件,文件内容指定具体的ServletContainerInitializer实现类,那么,当web容器启动时就会运行这个初始化器做一些
组件内的初始化工作。一般伴随着ServletContainerInitializer一起使用的还有HandlesTypes注解,通过HandlesTypes可以将感兴趣的一些类注入到ServletContainerInitializerde的onStartup方法作为参数传入。

tomcat7之后的版本都实现了servlet3.0的SPI规范。

servlet3.0之前开发一个web应用必须要配置web.xml作为web应用的入口,定义一个servlet也必须在web.xml中定义才能够被加载;servlet3.0之后,web容器(tomcat)在进行初始化时,根据SPI规范会调用实现了javax.servlet.ServletContainerInitializer接口的类的onStartup方法,servlet可以在onStartup方法中定义,这就可以省略web.xml。springboot也是基于这个原理,所以在springboot中已经看不到web.xml的踪影。

SpringServletContainerInitializer

springmvc 提供了一个类SpringServletContainerInitializer,满足了上面个条件。

所以 SpringServletContainerInitializer 的 onStart 方法会 servlet 容器自动被调用。

源码:SpringServletContainerInitializer 

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web;

import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;

@HandlesTypes({WebApplicationInitializer.class})
public class SpringServletContainerInitializer implements ServletContainerInitializer {
    public SpringServletContainerInitializer() {
    }

    public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
        List<WebApplicationInitializer> initializers = new LinkedList();
        Iterator var4;
        if (webAppInitializerClasses != null) {
            var4 = webAppInitializerClasses.iterator();

            while(var4.hasNext()) {
                Class<?> waiClass = (Class)var4.next();
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((WebApplicationInitializer)ReflectionUtils.accessibleConstructor(waiClass, new Class[0]).newInstance());
                    } catch (Throwable var7) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", var7);
                    }
                }
            }
        }
        if (initializers.isEmpty()) {
            servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
        } else {
            servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
            AnnotationAwareOrderComparator.sort(initializers);
            var4 = initializers.iterator();
            while(var4.hasNext()) {
                WebApplicationInitializer initializer = (WebApplicationInitializer)var4.next();
                //关键代码
                initializer.onStartup(servletContext);
            }
        }
    }
}

我们发现SpringServletContainerInitializer类上有@HandlesTypes(WebApplicationInitializer.class) 这个注解,注解的值为WebApplicationInitializer.class,所以 onStartup 方法的第一个参数是WebApplicationInitializer类型的集合,这个集合由 web 容器自动扫描获取,然后传入进来。

  • 实例化 WebApplicationInitializer 集合
  • 对 WebApplicationInitializer 集合进行排序
  • 循环调用 WebApplicationInitializer 的 onStartup 方法

WebApplicationInitializer web应用初始化

接口比较简单,就一个方法,参数是 servlet 上下文对象,有了个对象,可以干 web.xml 中的一切事情了,比如注册 servlet、filter、监听器等等。

public interface WebApplicationInitializer {
    void onStartup(ServletContext servletContext) throws ServletException;
}

看一下类的继承关系:

关键代码都在三个抽象类中。

我们全注解使用Spring(不需要web.xml文件)就需要继承AbstractAnnotationConfigDispatcherServletInitializer类。

AbstractDispatcherServletInitializer#onStartup 

public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    registerDispatcherServlet(servletContext);
}

这里是重点:这个方法中干了4件事情。

  • 创建父容器,只是实例化了,并未启动
  • 创建了监听器 ContextLoaderListener,这是一个 ServletContextListener 类型的监听器,稍后会在这个监听器中启动父容器
  • 创建springmvc容器,只是实例化了,并未启动,启动的事情会在 DispatcherServlet#init 中做
  • Servlet 容器中注册 DispatcherServlet

创建父容器

父容器可有可无,并不是必须的,为了更好的管理 bean,springmvc 建议我们用父子容器,controller 之外的 bean,比如 service,dao 等,建议放到父容器中,controller 层的和 springmvc 相关的一些 bean 放在 springmvc 容器中。

1)AbstractDispatcherServletInitializer#onStartup方法中会调用父类的onStartup,即AbstractContextLoaderInitializer#onStartup

2)负责创建父容器

AbstractAnnotationConfigDispatcherServletInitializer#createRootApplicationContext,只是创建了一个AnnotationConfigWebApplicationContext对象,并将父容器配置类 rootConfigClass 注册到容器中,并没有启动这个容器,若 rootConfigClass 为空,父容器不会被创建,所以父容器可有可无。

3)创建 ContextLoaderListener 监听器

ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
//getRootApplicationContextInitializers()返回置为ApplicationContextInitializer数组,是个函数式接口,在父容器初始化的过程中,会作为一个扩展点预留给开发者用
listener.setContextInitializers(getRootApplicationContextInitializers());
servletContext.addListener(listener);

ContextLoaderListener,这是一个 ServletContextListener 类型的监听器,在 web 容器启动和销毁的过程中会被调用。

contextInitialized方法:会在 web 容器启动时被调用,内部负责启动父容器

contextDestroyed方法:会在 web 容器销毁时被调用,内部负责关闭父容器

创建 springmvc 容器&注册 DispatcherServlet

registerDispatcherServlet源码如下:

protected void registerDispatcherServlet(ServletContext servletContext) {
    //①:DispatcherServlet的servlet名称,默认为:dispatcher
    String servletName = getServletName();

    //②:创建springmvc容器
    WebApplicationContext servletAppContext = createServletApplicationContext();

    //③:创建DispatcherServlet,注意这里将springmvc容器对象做为参数传递给DispatcherServlet了
    FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
    //设置ApplicationContextInitializer列表,可以对springmvc容器在启动之前进行定制化
    dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());

    //④:将 dispatcherServlet 注册到servlet上下文中
    ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
    registration.setLoadOnStartup(1);
    registration.addMapping(getServletMappings());
    registration.setAsyncSupported(isAsyncSupported());

    //⑤:注册Filter
    Filter[] filters = getServletFilters();
    if (!ObjectUtils.isEmpty(filters)) {
        for (Filter filter : filters) {
            registerServletFilter(servletContext, filter);
        }
    }
    //⑥:这个方法预留给咱们自己去实现,可以对dispatcherServlet做一些特殊的配置
    customizeRegistration(registration);
}

protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
    return new DispatcherServlet(servletAppContext);
}

启动父容器:ContextLoaderListener

AbstractDispatcherServletInitializer#onStartup方法执行完毕之后,会执行监听器ContextLoaderListener的初始化,会进入到它的contextInitialized方法中

initWebApplicationContext源码如下,截取了主要的几行:

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    //this.context就是父容器对象
    ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
    //①:配置及启动父容器
    configureAndRefreshWebApplicationContext(cwac, servletContext);
    //将父容器丢到servletContext中进行共享,方便其他地方获取
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
}

配置父容器以及启动父容器

//①:配置及启动父容器
configureAndRefreshWebApplicationContext(cwac, servletContext);

configureAndRefreshWebApplicationContext方法关键代码如下:

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
    //①:定制上线文,这里主要是遍历ApplicationContextInitializer列表,调用每个ApplicationContextInitializer#initialize方法来对容器进行定制,相当于一个扩展点,可以有程序员自己控制
    customizeContext(sc, wac);
    //②:刷新容器,就相当于启动容器了,此时就会组装里面的bean了
    wac.refresh();
}

customizeContext方法会遍历ApplicationContextInitializer列表,调用其initialize方法。

这是spring给开发者留的一个扩展点,通过ApplicationContextInitializer这个来做扩展。

启动springmvc容器:DispatcherServlet#init()

到目前为止父容器已经启动完毕了,此时 DispatcherServlet 会被初始化,会进入到它的 init()方法中。

DispatcherServlet类图

HttpServletBean#init()

这个方法会调用initServletBean()这个方法

 

FrameworkServlet#initServletBean

提取了2行关键的代码

@Override
protected final void initServletBean() throws ServletException {
    //初始化springmvc容器,就是启动springmvc容器
    this.webApplicationContext = initWebApplicationContext();
    //这个方法内部是空的,预留给子类去实现的,目前没啥用
    initFrameworkServlet();
}

FrameworkServlet#initWebApplicationContext

  • 从 servlet上下文对象中找到父容器
  • 为 springmvc 容器指定父容器
  • 调用 configureAndRefreshWebApplicationContext 方法配置 springmvc 容器以及启动容器
protected WebApplicationContext initWebApplicationContext() {
    //①:从servlet上线文中获取父容器
    WebApplicationContext rootContext =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    WebApplicationContext wac = null;
    //②:this.webApplicationContext就是springmvc容器,此时这个对对象不为null,所以满足条件
    if (this.webApplicationContext != null) {
        wac = this.webApplicationContext;
        if (wac instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
            //springmvc容器未启动
            if (!cwac.isActive()) {
                //springmvc容器未设置父容器,则给其设置父容器,此时rootContext可能为空,这个没什么关系
                if (cwac.getParent() == null) {
                    cwac.setParent(rootContext);
                }
                //③:配置springmvc容器以及启动springmvc容器
                configureAndRefreshWebApplicationContext(cwac);
            }
        }
    }
    //这里省略了一部分代码,如果springmvc采用配置文件的方式会走这部分代码
    //......
    //返回容器
    return wac;
}

FrameworkServlet#configureAndRefreshWebApplicationContext

提取了部分关键代码,主要干了这么几件事情:

  • 代码 ①:向 springmvc 容器中添加了一个 ContextRefreshListener 监听器,这个监听器非常非常重要,springmvc 容器启动完毕之后会被调用
  • 代码 ②:给开发者预留的一个扩展点,通过 ApplicationContextInitializer#initialize 方法对容器进行定制
  • 代码 ③:启动容器
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
    //①:向springmvc容器中添加了一个监听器对象,这个监听器特别重要
    wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
    //②:扩展点:循环遍历ApplicationContextInitializer列表,调用其initialize方法对容器进行定制
    applyInitializers(wac);
    //③:刷新容器,相当于启动容器
    wac.refresh();
}

springmvc 容器启动过程中处理@EnableWebMVC

SpringMVC 配置类被处理

此时 springmvc 容器启动了,注意下MvcConfig这个类,由于其上有@Conguration 注解,所以会被当做一个配置类被处理,这个类有 2 个非常重要的特征。

  • 标注了@EnableWebMvc 注解
  • 实现了 WebMvcConfigurer 接口

@EnableWebMvc:配置 springmvc 所需组件

看一下这个注解的源码,重点在于它上面的@Import(DelegatingWebMvcConfiguration.class)注解

 

进入 DelegatingWebMvcConfiguration 类

  • 代码编号 ①:标注有@Configuration 注解,说明是一个配置类
  • 代码编号 ②:继承了 WebMvcConfigurationSupport 类,这个类中有很多@Bean 标注的方法,用来定义了 springmvc 需要的所有组件
  • 代码编号 ③:注入了WebMvcConfigurer列表,注意下,我们的 WebConfig 类就实现了 WebMvcConfigurer 这个接口,内部提供了很多方法可以用来对 springmvc 的组件进行自定义配置

 

WebMvcConfigurationSupport:配置 springmvc 所需所有组件

这个类中会定义 springmvc 需要的所有组件,比如:RequestMapping、HandlerAdapter、HandlerInterceptor、HttpMessageConverter、HandlerMethodArgumentResolver、HandlerMethodReturnValueHandler 等等,所以如果你感觉@EnableWebMVC 注解满足不了你的需求时,你可以直接继承这个类进行扩展。

WebMvcConfigurer接口

这个接口就是我们用来对 springmvc 容器中的组件进行定制的,WebMvcConfigurationSupport 中创建 springmvc 组件的时候,会自动调用 WebMvcConfigurer 中对应的一些方法,来对组件进行定制,比如可以在 WebMvcConfigurer 中添加拦截器、配置默认 servlet 处理器、静态资源处理器等等,这个接口的源码如下:

public interface WebMvcConfigurer {

    /**
      * 配置PathMatchConfigurer
      */
    default void configurePathMatch(PathMatchConfigurer configurer) {
    }

    /**
      * 配置ContentNegotiationConfigurer
      */
    default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    }

    /**
      * 异步处理配置
      */
    default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
    }

    /**
      * 配置默认servlet处理器
      */
    default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    }

    /**
      * 配置Formatter
      */
    default void addFormatters(FormatterRegistry registry) {
    }

    /**
      * 添加拦截器
      */
    default void addInterceptors(InterceptorRegistry registry) {
    }

    /**
      * 静态资源配置
      */
    default void addResourceHandlers(ResourceHandlerRegistry registry) {
    }

    /**
      * 跨越的配置
      */
    default void addCorsMappings(CorsRegistry registry) {
    }

    /**
      * 配置ViewController
      */
    default void addViewControllers(ViewControllerRegistry registry) {
    }

    /**
      * 注册视图解析器(ViewResolverRegistry)
      */
    default void configureViewResolvers(ViewResolverRegistry registry) {
    }

    /**
      * 注册处理器方法参数解析器(HandlerMethodArgumentResolver)
      */
    default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
    }

    /**
      * 注册处理器方法返回值处理器(HandlerMethodReturnValueHandler)
      */
    default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
    }

    /**
      * 注册http报文转换器(HttpMessageConverter)
      */
    default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    }

    /**
      * 扩展报文转换器
      */
    default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    }

    /**
      * 配置异常解析器(HandlerExceptionResolver)
      */
    default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
    }

    /**
      * 扩展异常解析器(HandlerExceptionResolver)
      */
    default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
    }

    /**
      * 获得验证器
      */
    @Nullable
    default Validator getValidator() {
        return null;
    }

    /**
      * 获得MessageCodesResolver
      */
    @Nullable
    default MessageCodesResolver getMessageCodesResolver() {
        return null;
    }

}

组装DispatcherServlet中各种 SpringMVC 需要的组件

触发 ContextRefreshListener 监听器

springmvc 容器启动完毕之后,会发布一个ContextRefreshedEvent事件,会触发上面ContextRefreshListener 监听器的执行

进入FrameworkServlet.this.onApplicationEvent(event);

public void onApplicationEvent(ContextRefreshedEvent event) {
    //标记已收到刷新事件
    this.refreshEventReceived = true;
    synchronized (this.onRefreshMonitor) {
        onRefresh(event.getApplicationContext());
    }
}

上面的onRefresh(event.getApplicationContext());会进到DispatcherServlet#onRefresh方法中。

进入DispatcherServlet#onRefresh

protected void onRefresh(ApplicationContext context) {
    initStrategies(context);
}

里面会调用initStrategies方法。

DispatcherServlet#initStrategies:初始化 DispatcherServlet 中的组件

这里面会初始化 DispatcherServlet 中的各种组件,这里的所有方法初始化的过程基本上差不多,就是先从 springmvc 容器中找这个组件,如果找不到一般会有一个兜底的方案。

protected void initStrategies(ApplicationContext context) {
    //初始化MultipartResolver
    initMultipartResolver(context);
    //初始化LocaleResolver
    initLocaleResolver(context);
    //初始化ThemeResolver
    initThemeResolver(context);
    //初始化HandlerMappings
    initHandlerMappings(context);
    //初始化HandlerAdapters
    initHandlerAdapters(context);
    //初始化HandlerExceptionResolvers
    initHandlerExceptionResolvers(context);
    //初始化RequestToViewNameTranslator
    initRequestToViewNameTranslator(context);
    //初始化视图解析器ViewResolvers
    initViewResolvers(context);
    //初始化FlashMapManager
    initFlashMapManager(context);
}

销毁容器

销毁 springmvc 容器:DispatcherServlet#destroy

DispatcherServlet 销毁的时候会关闭 springmvc 容器。

public void destroy() {
    if (this.webApplicationContext instanceof ConfigurableApplicationContext && !this.webApplicationContextInjected) {
        ((ConfigurableApplicationContext) this.webApplicationContext).close();
    }
}

销毁父容器:ContextLoaderListener#contextDestroyed

父容器是在监听器中启动的,所以销毁的也是监听器负责的。

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

 

posted @ 2023-12-09 19:47  残城碎梦  阅读(269)  评论(0编辑  收藏  举报