0. 概述
分析web項(xiàng)目中spring的配置,初始化,bean解析和注入的過(guò)程,以及spring bean 的生命周期和擴(kuò)展點(diǎn),深入學(xué)習(xí)spring框架的使用。
示例項(xiàng)目: springinside
1. spring web 配置文件
項(xiàng)目常見(jiàn)的spring web 的web.xml, 這里去掉了一些無(wú)關(guān)的配置,盡量最小化配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<description>spring inside</description>
<display-name>spring inside</display-name>
<servlet-name>springinside</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springinside</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
- 配置context-param,contextConfigLocation 指定ContextLoaderListener使用的配置文件
- 配置了ContextLoaderListener,監(jiān)聽(tīng)web容器的啟動(dòng),用于做些初始化工作
- 配置了DispatcherServlet處理web請(qǐng)求,指定了DispatcherServlet要加載的配置文件
對(duì)于spring web 項(xiàng)目來(lái)說(shuō),其中1和2不是必須的,可以沒(méi)有。但是,這里配置ContextLoaderListener,是為了和部門(mén)的項(xiàng)目一致。部門(mén)的sof開(kāi)發(fā)框架在web容器啟動(dòng)的時(shí)候有一些初始化操作,就是在ContextLoaderListener這里觸發(fā)的。接下來(lái)我們分析ContextLoaderListener和DispatcherServlet源碼,來(lái)看看spring是怎么完成初始化的。
2. ContextLoaderListener分析
2.1 繼承關(guān)系
首先,看一下ContextLoaderListener的繼承關(guān)系

可以看到,ContextLoaderListener實(shí)現(xiàn)了ServletContextListener接口。ServletContextListener接口夠監(jiān)聽(tīng) ServletContext 對(duì)象的生命周期,實(shí)際上就是監(jiān)聽(tīng) Web應(yīng)用的生命周期。當(dāng)Servlet 容器啟動(dòng)或終止Web 應(yīng)用時(shí),會(huì)觸發(fā)ServletContextEvent 事件,該事件由ServletContextListener 來(lái)處理。
public interface ServletContextListener extends EventListener {
/**
** Notification that the web application initialization
** process is starting.
** All ServletContextListeners are notified of context
** initialization before any filter or servlet in the web
** application is initialized.
*/
public void contextInitialized ( ServletContextEvent sce );
/**
** Notification that the servlet context is about to be shut down.
** All servlets and filters have been destroy()ed before any
** ServletContextListeners are notified of context
** destruction.
*/
public void contextDestroyed ( ServletContextEvent sce );
}
當(dāng)Servlet啟動(dòng)時(shí)就會(huì)調(diào)用contextInitialized方法;當(dāng)Servlet銷(xiāo)毀時(shí)會(huì)調(diào)用contextDestroyed方法。
2.2 ContextLoaderListener
接下來(lái)我們看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());
}
}
ContextLoaderListener的代碼很簡(jiǎn)單,在Servlet啟動(dòng)時(shí),調(diào)用initWebApplicationContext方法初始化WebApplicationContext這個(gè)web應(yīng)用上下文;在Servlet銷(xiāo)毀時(shí),關(guān)閉應(yīng)用上下文。Spring是怎么初始化web應(yīng)用上下文的,我們跟蹤代碼進(jìn)入initWebApplicationContext方法一探究竟。
2.3 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;
}
}
initWebApplicationContext方法一共做了三件事:
1. 如果this.context為null, 則創(chuàng)建WebApplicationContext
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
我們?cè)趙eb.xml里,只配置了一個(gè)Listener,所以在ContextLoaderListener之前沒(méi)有創(chuàng)建過(guò)WebApplicationContext,固這里this.context為null,所以會(huì)創(chuàng)建WebApplicationContext。
2. 如果this.context是ConfigurableWebApplicationContext的實(shí)例,并且沒(méi)有刷新過(guò)WebApplicationContext,則配置并刷新WebApplicationContext。
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);
}
}
什么意思呢?首先,我們看看this.context的起繼承關(guān)系 。

this.contexnt的類(lèi)型是WebApplicationContext, 可以看到WebApplicationContext是個(gè)接口,它繼承了BeanFactory。this.context是Spring的IoC容器,所以下面的配置和刷新應(yīng)用上下文就不足為奇了,因?yàn)樗馕觯⑷隻ean。所以configureAndRefreshWebApplicationContext方法,會(huì)完成bean解析,加載,注入的過(guò)程?,F(xiàn)在我們知道了WebApplicationContext是一個(gè)接口,這里的this.context到底會(huì)是什么那個(gè)具體的實(shí)例呢?其實(shí),這里的this.context是XmlWebApplicationContext的具體實(shí)例。我們看一下XmlWebApplicationContext的繼承關(guān)系。

可以看到,XmlWebApplicationContext實(shí)現(xiàn)了ConfigurableWebApplicationContext 接口,ConfigurableWebApplicationContext 繼承了WebApplicationContext。繼承關(guān)系理清楚了,這里的代碼也就很容易看懂了。
3. 將WebApplicationContext放入servletContext中,供后續(xù)流程使用
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
這里講this.context放入servletContext中,后續(xù)的DispatcherServlet會(huì)從servletContext取出該容器,作為其創(chuàng)建的容器的父容器。
2.4 configureAndRefreshWebApplicationContext 分析
現(xiàn)在我們進(jìn)入configureAndRefreshWebApplicationContext方法,看看是如何配置和刷新上下文的。
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();
}
方法進(jìn)來(lái)首先檢查是否設(shè)置過(guò)id,如果沒(méi)有設(shè)置過(guò)id,那么就設(shè)置容器id。
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()));
}
}
容器id優(yōu)先從配置文web.xml中獲取,如果配置文件配置了容器id,那個(gè)就使用配置的容器id,否則使用默認(rèn)生成的容器id。
然后是獲取spring配置文件。配置文件也是我們?cè)趙eb.xml配置的context-param
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/*.xml</param-value>
</context-param>
Spring的環(huán)境配置,暫時(shí)不深入了解,后續(xù)在學(xué)習(xí)Spring的bean裝配時(shí)在介紹。
接下來(lái)是一個(gè)擴(kuò)展點(diǎn)————定制上下文,在容器刷新之前,給用戶(hù)一個(gè)機(jī)會(huì),可以做一些事情。
customizeContext(sc, wac);
跟進(jìn)去看看
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);
}
}
怎么定制上下文呢?看代碼可以知道,要實(shí)現(xiàn)ApplicationContextInitializer接口
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {
/**
* Initialize the given application context.
* @param applicationContext the application to configure
*/
void initialize(C applicationContext);
}
接口就一個(gè)初始化方法,傳入上下文。實(shí)現(xiàn)該接口,自己操作上下文,完成定制。實(shí)現(xiàn)了ApplicationContextInitializer接口之后,怎么配置讓其生效呢?我們先看看是怎么找實(shí)現(xiàn)該接口的類(lèi)的,進(jìn)入determineContextInitializerClasses看看。
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;
}
可以看到,這里是通過(guò) servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM)和servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM) 獲取類(lèi)名,和Spring配置文件一樣,也是在web.xml中配置的。
最后是刷新上下文。
這里的刷新上下文,其實(shí)就是Spring讀取配置穩(wěn)定,解析bean定義,注冊(cè)BeanDefinition,實(shí)例化bean,完成注入的過(guò)程,在此暫不深入。
wac.refresh();
3. DispatcherServlet分析
3.1繼承關(guān)系

DispatcherServlet間接實(shí)現(xiàn)了Servlet接口。在初始化階段,會(huì)調(diào)用Servlet的init()方法,這是Servlet的入口,接下來(lái)我們找到入口,從入口分析。
3.2 追根溯源 Servlet的init()
本次分析的目的是研究DispatcherServlet的上下文和ContextLoaderListener的上下文是如何初始化和關(guān)聯(lián)起來(lái)的,其它邏輯不是本文重點(diǎn),將會(huì)被忽略。
在GenericServlet類(lèi)中實(shí)現(xiàn)了Servlet接口的init方法
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
GenericServlet的init(ServletConfig config)方法除了設(shè)置了config并沒(méi)有干其它的邏輯,而是調(diào)用了自身的init()方法,將具體邏輯委托給自己的子類(lèi)處理。我們接著找誰(shuí)實(shí)現(xiàn)了init()方法。在HttpServletBean類(lèi)中找到了init()方法,看一下代碼
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// Let subclasses do whatever initialization they like.
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
HttpServletBean的init()方法也沒(méi)有看到有處理上下文的邏輯,但是看了initServletBean()這個(gè)方法,我們繼續(xù)跟代碼。
在FrameworkServlet類(lèi)中重寫(xiě)了initServletBean()方法。
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis();
try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
catch (RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}
在這里終于看到了與上下文有關(guān)的邏輯————initWebApplicationContext()方法,跟之。
protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
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) {
// 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) {
// 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.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
我們看我們感興趣的邏輯。
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
.
.
.
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
這里獲取根上下文rootContext,并將rootContext作為參數(shù),創(chuàng)建WebApplicationContext。這里獲取的rootContext就是在ContextLoaderListener設(shè)置的WebApplicationContext。Talk is cheap. Show me the code.
public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}
看到 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,我們回憶一下ContextLoaderListener是怎么設(shè)置上下文到ServletContext的。
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
證據(jù)確鑿。
再來(lái)看createWebApplicationContext(rootContext)
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
return createWebApplicationContext((ApplicationContext) parent);
}
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
Class<?> contextClass = getContextClass();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name '" + getServletName() +
"' will try to create custom WebApplicationContext context of class '" +
contextClass.getName() + "'" + ", using parent context [" + parent + "]");
}
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);
wac.setEnvironment(getEnvironment());
wac.setParent(parent);
wac.setConfigLocation(getContextConfigLocation());
configureAndRefreshWebApplicationContext(wac);
return wac;
}
看到createWebApplicationContext方法的代碼,是不是似曾相識(shí)的感覺(jué)?這和ContextLoaderListener的 initWebApplicationContext方法的邏輯是不是很相似?
wac.setParent(parent);
我們將目光放在上面一行代碼上。這行代碼將ContextLoaderListener的創(chuàng)建的WebApplicationContext和DispatcherServlet創(chuàng)建的WebApplicationContext關(guān)聯(lián)了起來(lái),將Web應(yīng)用上下文的層次體現(xiàn)出來(lái),我們也知道WebApplicationContext其實(shí)也是Spring的BeanFactory,所以這里也是設(shè)置了Spring Ioc容器的父子關(guān)系。最后就是configureAndRefreshWebApplicationContext了,這里就不分析了。