监听器的作用:监听器是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或者属性改变,当被监听对象发生上述事件后,监听器某个方法将立即执行。
Spring中org.springframework.web.context.ContextLoaderListener类监听器也是实现了ServletContextListener这个接口。作用是加载了spring的配置文件
<!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> // 实现了接口 ServletContextListener, 也就是说他必须实现 contextDestroyed, contextInitialized 这两个方法 public class ContextLoaderListener implements ServletContextListener { private ContextLoader contextLoader; /** * Initialize the root web application context. */ //Spring 框架由此启动 , contextInitialized 也就是监听器类的 main 入口函数 public void contextInitialized (ServletContextEvent event) { this.contextLoader = createContextLoader(); this.contextLoader.initWebApplicationContext(event.getServletContext()); } /** * Create the ContextLoader to use. Can be overridden in subclasses. * @return the new ContextLoader */ protected ContextLoader createContextLoader() { return new ContextLoader(); } /** * Return the ContextLoader used by this listener. * @return the current ContextLoader */ public ContextLoader getContextLoader() { return this.contextLoader; } /** * Close the root web application context. */ public void contextDestroyed (ServletContextEvent event) { if (this.contextLoader != null) { this.contextLoader.closeWebApplicationContext(event.getServletContext()); } } }