传统的Spring MVC工程是以WAR文件部署的,本文分析传统的Spring MVC工程在servlet容器中的启动过程,如未特别说明,本系列使用的Spring版本是4.3.18.RELEASE。
部署描述符
在传统的Spring MVC工程中,WEB-INF目录下都有一个web.xml文件,它其实是Web应用部署描述符(Web Application Deployment Descriptor),示例如下。
spring mvc
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
/WEB-INF/spring/applicationContext.xml
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring/dispatcherServlet.xml
0
dispatcher
/*
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*
部署描述符有以下部分组成:
元素定义了Web应用的事件监听器; 元素定义了Web应用的ServletContext的初始化参数; 元素定义了ServletContext包含的servlet; 元素定义了servlet的映射模式; 元素定义了ServletContext包含的过滤器; 元素定义了过滤器的映射模式; - ...
根据servlet 3.1规范10.12节,当Web应用被部署到容器时,在处理请求之前会按顺序发生如下事情:
- 为部署描述符中每个
元素标识的事件监听器创建一个实例; - 为实现了ServletContextListener接口的监听器实例调用其contextInitialized()方法;
- 为部署描述符中每个
元素标识的过滤器创建一个实例,并调用其init()方法; - 为部署描述符中每个
元素中含有 的servlet按load-on-startup值的顺序创建一个实例,并调用其init()方法。
上述web.xml只有一个ContextLoaderListener类型的监听器,接下来就详细看一下这个监听器。
ContextLoaderListener类
ContextLoaderListener类继承了ContextLoader类,同时实现了ServletContextListener接口。根据servlet 3.1规范11.3.1节,每个监听器类必须有一个公共的无参构造函数,其在被容器实例化后调用contextInitialized方法。ContextLoaderListener类很简单,代码如下:
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
/**
* Initialize the root web application context.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
/**
* Close the root web application context.
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
contextInitialized方法调用了父类ContextLoader的initWebApplicationContext方法初始化根应用上下文(root web application context)。
ContextLoader类
成员变量和构造函数
ContextLoader类的成员变量和构造函数如下所示:
public class ContextLoader {
public static final String CONTEXT_ID_PARAM = "contextId";
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";
public static final String CONTEXT_CLASS_PARAM = "contextClass";
public static final String CONTEXT_INITIALIZER_CLASSES_PARAM = "contextInitializerClasses";
public static final String GLOBAL_INITIALIZER_CLASSES_PARAM = "globalInitializerClasses";
public static final String LOCATOR_FACTORY_SELECTOR_PARAM = "locatorFactorySelector";
public static final String LOCATOR_FACTORY_KEY_PARAM = "parentContextKey";
private static final String INIT_PARAM_DELIMITERS = ",; \t\n";
private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
private static final Properties defaultStrategies;
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
private static final Map currentContextPerThread =
new ConcurrentHashMap(1);
private static volatile WebApplicationContext currentContext;
private WebApplicationContext context;
private BeanFactoryReference parentContextRef;
/** Actual ApplicationContextInitializer instances to apply to the context */
private final List> contextInitializers =
new ArrayList>();
public ContextLoader() {
}
public ContextLoader(WebApplicationContext context) {
this.context = context;
}
// 省略一些代码
}
- 很多变量都能对应到
元素表示的初始化参数名,如CONFIG_LOCATION_PARAM的值是contextConfigLocation,CONTEXT_CLASS_PARAM的值是contextClass等; - INIT_PARAM_DELIMITERS表示初始化参数值的分隔符,如contextConfigLocation参数的值可以用逗号分隔多个文件;
- defaultStrategies是一个Properties类型的变量,ContextLoader类的静态代码块会从与它同目录的ContextLoader.properties文件中读取属性值并保存到defaultStrategies。
# 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
初始化根应用上下文
ContextLoaderListener类在ServletContext初始化时调用了initWebApplicationContext方法初始化整个工程的根应用上下文,该方法代码如下所示:
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
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) {
// 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);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
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");
}
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是否有WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE表示的属性,如果有那么说明根上下文已经存在,抛出异常。这个属性在随后FrameworkServlet类的initWebApplicationContext方法中也会用到,用来为servlet自己的应用上下文寻找根应用上下文;
- 接着创建、配置并刷新根应用上下文;
- 根应用上下文创建成功后,调用ServletContext类的setAttribute方法将以WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE为键、以根应用上下文为值的属性保存在ServletContext中。
创建根应用上下文
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);
}
protected Class> determineContextClass(ServletContext servletContext) {
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);
}
}
}
- 若存在名为contextClass的初始化参数,那么创建contextClass类型的应用上下文,否则创建defaultStrategies变量里保存的XmlWebApplicationContext类型的应用上下文;
- 从抛出异常的判断可以看到contextClass初始化参数的值必须是ConfigurableWebApplicationContext的子类。
配置并刷新根应用上下文
configureAndRefreshWebApplicationContext方法用于配置并刷新根应用上下文,主要执行初始化参数赋值、ApplicationContextInitializer接口的回调和实例化根应用上下文中的bean等工作。
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()));
}
}
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) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
wac.refresh();
}
该方法按顺序做了如下工作:
- 若存在contextId和contextConfigLocation初始化参数,则将各参数值绑定到根应用上下文;
- 调用customizeContext方法执行各ApplicationContextInitializer的initialize回调函数;
- 刷新根应用上下文,实例化其中的单例bean。
customizeContext方法
在customizeContext方法中,各ApplicationContextInitializer的initialize回调函数被依次调用,其代码如下:
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
List>> initializerClasses =
determineContextInitializerClasses(sc);
for (Class> 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 initializer : this.contextInitializers) {
initializer.initialize(wac);
}
}
protected List>>
determineContextInitializerClasses(ServletContext servletContext) {
List>> classes =
new ArrayList>>();
String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM);
if (globalClassNames != null) {
for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) {
classes.add(loadInitializerClass(className));
}
}
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;
}
需要关注的点如下:
- determineContextInitializerClasses方法从部署描述符中找到名为globalInitializerClasses的
初始化参数和名为contextInitializerClasses的 初始化参数指定的ApplicationContextInitializer实现类; - 这两个参数的参数值都是由各个类名组成的以逗号、分号或空白符分隔的字符串。不同点在于contextInitializerClasses初始化参数指定的类只用于根应用上下文,而globalInitializerClasses初始化参数指定的类会用于所有的应用上下文(既包括根应用上下文,也包括FrameworkServlet自己的应用上下文);
- ApplicationContextInitializer实现类必须有一个无参构造函数,可以选择地实现Ordered接口或使用@Order注解以达到按顺序执行的目的。
实例化Filter与Servlet
根应用上下文被创建后,容器会接着实例化Filter与Servlet,请看后续文章对DispatcherServlet初始化过程的分析。
参考文献
Servlet 3.1规范