public class ContextLoaderListener extends ContextLoader implements ServletContextListener{}
ServletContextListenter是J2ee Servlet标准的一部分,用于监听ServletContext的启动和销毁;
public interface ServletContextListener extends EventListener { /** * Receives notification that the web application initialization * process is starting. * * <p>All ServletContextListeners are notified of context * initialization before any filters or servlets in the web * application are initialized. * * @param sce the ServletContextEvent containing the ServletContext * that is being initialized */ public void contextInitialized(ServletContextEvent sce); /** * Receives notification that the ServletContext is about to be * shut down. * * <p>All servlets and filters will have been destroyed before any * ServletContextListeners are notified of context * destruction. * * @param sce the ServletContextEvent containing the ServletContext * that is being destroyed */ public void contextDestroyed(ServletContextEvent sce); }
EventListener是事件标志接口
/** * A tagging interface that all event listener interfaces must extend. * @since JDK1.1 */ public interface EventListener { }
Servlet生命周期
Web容器启动 加载Web.xml中配置的Servlet 第一次开始调用 开始应用期间的一次初始化; 当应用停止 Servlet调用Destoryed;
ServletContext
代表着web应用一个应用只有一个记录整个应用的信息;
总结:ContextLoadListener实现ServletContextListener是为了在应用启动或者关闭时做一些必要的工作;
/** * 重写了ServletContext初始化监听 * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); } /** *重写了ServletContext销毁监听 * Close the root web application context. */ @Override public void contextDestroyed(ServletContextEvent event) { closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); }
主要用于创建WebApplicationContext;
可以在通过web.xml 的initParam来指定默认的WebApplicationContext的实现类就会采用XmlWebApplicationContext来当做默认;WebApplicationContext是存储在ServletContext中的应用级变量;并且是唯一的!
在创建过程:
1,获得加载类 CurrTheadClassLoader 或者 ClassUtils.class.getClassLoader(); 或者 ClassLoader.getSystemClassLoader();
2,开始通过加载类获得Class
3,通过Class的反射构造 newInstance