ServletContextListener是servlet容器中的一個(gè)API接口, 它用來(lái)監(jiān)聽ServletContext的生命周期赏枚,也就是相當(dāng)于用來(lái)監(jiān)聽Web應(yīng)用的生命周期友扰。今天我們就來(lái)說(shuō)說(shuō)如何在Springboot 1.5.2這個(gè)輕量型框架中如何使用它。
其實(shí)配置ServletContextListener與其它Filter, Listener, Servlet方法是一致的瘩欺,具體可參考Springboot 1.5.2 官方文檔
首先寫一個(gè)類來(lái)實(shí)現(xiàn)ServletContextListener接口,并實(shí)現(xiàn)contextInitialized(), contextDestroyed()兩個(gè)父類方法,并使用@WebListener注解, 具體代碼如下:
package org.liting;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebListener
public class PmsServletContextListener implements ServletContextListener{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
logger.info("liting: contextDestroyed");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
logger.info("liting: contextInitialized");
}
}
2氯檐、其次在Springboot web 應(yīng)用啟動(dòng)代碼中添加@ServletComponentScan注解,使我們的Springboot應(yīng)用在啟動(dòng)時(shí)能掃描到該Listener.
運(yùn)行項(xiàng)目体捏,我們可以springboot的啟動(dòng)log看到如下log信息冠摄,即表明我們的ServletContextListener注冊(cè)成功糯崎。
@SpringBootApplication
@EnableTransactionManagement
@ServletComponentScan
@MapperScan("com.xsxx.mapper")//配置mybatis包掃描