傳統的Spring MVC工程是以WAR文件部署的,本文分析傳統的Spring MVC工程在servlet容器中的啟動過程,如未特別說明,本系列使用的Spring版本是4.3.18.RELEASE。
部署描述符
在傳統的Spring MVC工程中,WEB-INF目錄下都有一個web.xml文件,它其實是Web應用部署描述符(Web Application Deployment Descriptor),示例如下。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>spring mvc</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcherServlet.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
部署描述符有以下部分組成:
- <listener>元素定義了Web應用的事件監聽器;
- <context-param>元素定義了Web應用的ServletContext的初始化參數;
- <servlet>元素定義了ServletContext包含的servlet;
- <servlet-mapping>元素定義了servlet的映射模式;
- <filter>元素定義了ServletContext包含的過濾器;
- <filter-mapping>元素定義了過濾器的映射模式;
- ...
根據servlet 3.1規范10.12節,當Web應用被部署到容器時,在處理請求之前會按順序發生如下事情:
- 為部署描述符中每個<listener>元素標識的事件監聽器創建一個實例;
- 為實現了ServletContextListener接口的監聽器實例調用其contextInitialized()方法;
- 為部署描述符中每個<filter>元素標識的過濾器創建一個實例,并調用其init()方法;
- 為部署描述符中每個<servlet>元素中含有<load-on-startup>的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<ClassLoader, WebApplicationContext> currentContextPerThread =
new ConcurrentHashMap<ClassLoader, WebApplicationContext>(1);
private static volatile WebApplicationContext currentContext;
private WebApplicationContext context;
private BeanFactoryReference parentContextRef;
/** Actual ApplicationContextInitializer instances to apply to the context */
private final List<ApplicationContextInitializer<ConfigurableApplicationContext>> contextInitializers =
new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();
public ContextLoader() {
}
public ContextLoader(WebApplicationContext context) {
this.context = context;
}
// 省略一些代碼
}
- 很多變量都能對應到<context-param>元素表示的初始化參數名,如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<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>>>();
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的<context-param>初始化參數和名為contextInitializerClasses的<context-param>初始化參數指定的ApplicationContextInitializer實現類;
- 這兩個參數的參數值都是由各個類名組成的以逗號、分號或空白符分隔的字符串。不同點在于contextInitializerClasses初始化參數指定的類只用于根應用上下文,而globalInitializerClasses初始化參數指定的類會用于所有的應用上下文(既包括根應用上下文,也包括FrameworkServlet自己的應用上下文);
- ApplicationContextInitializer實現類必須有一個無參構造函數,可以選擇地實現Ordered接口或使用@Order注解以達到按順序執行的目的。
實例化Filter與Servlet
根應用上下文被創建后,容器會接著實例化Filter與Servlet,請看后續文章對DispatcherServlet初始化過程的分析。