因为WebApplicationContext 需要ServletContext 实例,也就是说它必须在拥有Web 容器的前提下才能完成启动的工作。有过Web 开发经验的读者都知道可以在web.xml 中配置自启动的Servlet 或定义Web 容器监听器(ServletContextListener),借助这两者中的任何一个,我们就可以完成启动Spring Web 应用上下文的工作。
Spring 分别提供了用于启动WebApplicationContext 的Servlet 和Web 容器监听器:
org.springframework.web.context.ContextLoaderServlet;
org.springframework.web.context.ContextLoaderListener。
两者的内部都实现了启动WebApplicationContext 实例的逻辑,我们只要根据Web 容器的具体情况选择两者之一,并在web.xml 中完成配置就可以了。
你可以查看一下spring3.0的change log 里面注明:
removedContextLoaderServlet and Log4jConfigServlet 的确是去掉了
spring有三种启动方式,使用ContextLoaderServlet,ContextLoaderListener和ContextLoaderPlugIn
可以采用余下两种启动方式ContextLoaderListener和ContextLoaderPlugIn 建议使用ContextLoaderListener
![\](http://www.2cto.com/uploadfile/Collfiles/20140125/20140125091103127.jpg)
ContextLoaderListener相关配置的注意事项看Spring笔记1——控制反转容器
那通过ContextLoaderListener,Spring是怎么怎么初始化和配置Spring容器(WebApplicationContext)的呢?
Spring容器的初始化过程:
![\](http://www.2cto.com/uploadfile/Collfiles/20140125/20140125091103128.jpg)
接下来再详细从代码上介绍吧
ContextLoaderListener的体系结构
![\](http://www.2cto.com/uploadfile/Collfiles/20140125/20140125091103130.jpg)
部署spring例子到tomcat,运行tomcat
看到上面spring 和tomcat 结合,我们似乎想到spring和tomcat之间似乎有点什么关系
Tomcat(5.0以上)
加载时的织入配置 Apache Tomcat 缺省的ClassLoader(类装载器)并不支持类的切换, 但是它允许使用用户自定义的类装载器。Spring提供了 TomcatInstrumentableClassLoader 类 (在org.springframework.instrument.classloading.tomcat 包中),这个类继承自Tomcat的类装载器 (WebappClassLoader)并且允许JPA ClassTransformer 的实例来“增强”所有由它加载的类。 简单说,JPA转化器(JPA transformer)仅仅在(使用 TomcatInstrumentableClassLoader 的)特定web应用程序中才能被使用。
为使用用户自定义的类装载器: 将 spring-tomcat-weaver.jar 复制到 $CATALINA_HOME/server/lib 下 (其中$CATALINA_HOME 表示Tomcat的安装路径)。
通过修改web application context使Tomcat使用用户自定义的类装载器(而不是默认的类装载器):
<Context path="/myWebApp" docBase="/my/webApp/location">
<Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>
</Context>
1
2
3
4
5
6
7
8
|
ContextLoader
/**
* Initialize the root web application context.
*/
@Override
public
void
contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
|
再看一下ContextLoader的initWebApplicationContext()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
ContextLoader
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);
//这里根据ServletContext创建Spring容器(在这里创建的是XmlWebApplicationContext)
}
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);
//这里进行WebApplicationContext的配置工作,其中包括把servletContext和Spring容器关联起来,以及将配置文件(applicationContext.xml)加入到容器中
}
}
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;
}
}
|
再进入createWebApplicationContext()
1
2
3
4
5
6
7
8
9
|
//ContextLoader
protected
WebApplicationContext createWebApplicationContext(ServletContext sc) {
Class<!--?--> contextClass = determineContextClass(sc);
//返回WebApplicationContext实现类使用,默认XmlWebApplicationContext或如果指定一个自定义上下文类。
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);
}
|
再看determineConetxt()
![width=700](http://www.2cto.com/uploadfile/Collfiles/20140125/20140125091104135.jpg)
可以看到在这里其实就是根据Parameter CONTEXT_CLASSPARAM去实例化一个WebApplicatoinContext,而该参数其实在web.xml已经配置为XmlWebApplicationContext(WebApplicationContext实现类) ,看web.xml
1
2
3
4
5
6
7
8
|
//web.xml
<!-- 如果配置了contextClass上下文参数,就会用参数所指定的WebApplicationContext实现类初始话容器 -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.XmlWebApplicationContext
</param-value>
</context-param>
|
接着,我们回到initWebApplicationContext(),其中调用的configureAndRefreshWebApplicationContext(cwac, servletContext);我们看一下他的实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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);
//这里设置WebApplicationContext的id值为contextId也就是我们浏览器访问的localhost:8080/01/中的01
}
else
{
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);
//这里设置Web.xml中配置的contextConfigLocation参数,也就是配置文件applicationContext.xml了
if
(initParameter !=
null
) {
wac.setConfigLocation(initParameter);
}
customizeContext(sc, wac);
wac.refresh();
//加载刚才的配置文件applicationContext.xml,以及bean的实例化
}
|
![\](http://www.2cto.com/uploadfile/Collfiles/20140125/20140125091105136.jpg)
再看一下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
//XmlWebApplicationContext
@Override
public
void
refresh()
throws
BeansException, IllegalStateException {
synchronized
(
this
.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try
{
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch
(BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw
ex;
}
}
}
|
这个方法就是配置Spirng Web容器,根据applicationContext.xml实例化类的重中之重了,东西太多了,下篇博客再接着说吧
![\](http://www.2cto.com/uploadfile/Collfiles/20140125/20140125091103130.jpg)