标签:spring contextloaderlistener webapplicationcontext初始化
在spring和structs2整合中,在web.xml文件中需要设置一个listener,如下
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
ContextLoaderListener会在web容器初始化的时候进行初始化,然后进行初始化WebApplicationContext的工作。我们来看一下ContextLoaderListener的关键代码:
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}这段代码实现了WebApplicationContext初始化工作,在代码的最后一行调用了contextLoader的initWebApplicationContext的方法,我们再来看一下contextLoader的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);
}最后一行,又调用了createWebApplicationContext方法,我们再来看一下这个方法的代码:
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);
}通过代码可知,在这里返回了一个ConfigurableWebApplicationContext,再来看一下contextLoader的initWebApplicationContext方法中最关键的代码:
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
在这里把context存入servletContext中,所以以后要用到WebApplicationContext的时候可以从servletContext取出。
本文出自 “飞鱼技术” 博客,请务必保留此出处http://flyingfish.blog.51cto.com/9580339/1681334
Spring ContextLoaderListener 中WebApplicationContext初始化
标签:spring contextloaderlistener webapplicationcontext初始化
原文地址:http://flyingfish.blog.51cto.com/9580339/1681334