WEB容器監聽器ServletContextListener主要用來監聽容器啓動和 銷燬的時候須要作一些操做,就能夠使用這個監聽器來作。web
ServletContextListener在Spring啓動前啓動。
api
咱們實現一個簡單的監聽器,須要繼承接口ServletContextListener:app
* 一個測試的監聽器例子 ide
* @author zhuli 測試
* @date 2014-7-26 spa
*/ .net
public class TestContextLister implements ServletContextListener { 日誌
@Override orm
public void contextInitialized(ServletContextEvent sce) { xml
System.out.println("==============================容器裝載");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("==============================容器銷燬");
}
}
ServletContextListener 實現兩個接口,一個是容器啓動的時候,一個是容器銷燬的時候:
public interface ServletContextListener extends EventListener {
/**
** Notification that the web application initialization
** process is starting.
** All ServletContextListeners are notified of context
** initialization before any filter or servlet in the web
** application is initialized.
*/
public void contextInitialized ( ServletContextEvent sce );
/**
** Notification that the servlet context is about to be shut down.
** All servlets and filters have been destroy()ed before any
** ServletContextListeners are notified of context
** destruction.
*/
public void contextDestroyed ( ServletContextEvent sce );
}
在web.xml中的配置:
<listener>
<listener-class>com.xxx.controller.web.TestContextLister</listener-class>
</listener>
容器啓動後,會在容器啓動的日誌中看到:
==============================容器裝載
2014-07-26 08:54:01.302:INFO:/:Initializing Spring FrameworkServlet 'apiServlet'