ContextLoaderListener是ServletContextListener的一种实现,这个接口的作用就是监听ServletContext的生命周期内发生的事件,包括其初始化和销毁
public interface ServletContextListener extends EventListener {
/**
* Receives notification that the web application initialization
* process is starting.
*/
public void contextInitialized(ServletContextEvent sce);
/**
* Receives notification that the ServletContext is about to be
* shut down.
*/
public void contextDestroyed(ServletContextEvent sce);
}
在web.xml声明的ServeltContextListener必须拥有一个无参的构造方法;对象创建好之后就可以监听ServletContext的生命周期了;
当ServletContext初始化时,调用其初始化方法,对WebApplicationContext进行初始化。
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
创建好的ApplicationContext实例注册到ServletContext的属性中,其对应的属性名为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;并且当contextDestroyed被调用时这个Spring的ApplicationContext将会被关闭。
String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
其ApplicationContext是一个 org.springframework.web.context.support.XmlWebApplicationContext的实例