ServletContextListener在Springboot中的使用

ServletContextListener是servlet容器中的一個(gè)API接口, 它用來監(jiān)聽ServletContext的生命周期,也就是相當(dāng)于用來監(jiān)聽Web應(yīng)用的生命周期。今天我們就來說說如何在Springboot 1.5.2這個(gè)輕量型框架中如何使用它。
其實(shí)配置ServletContextListener與其它Filter, Listener, Servlet方法是一致的,具體可參考Springboot 1.5.2 官方文檔
首先寫一個(gè)類來實(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)用啟動代碼中添加@ServletComponentScan注解,使我們的Springboot應(yīng)用在啟動時(shí)能掃描到該Listener.

運(yùn)行項(xiàng)目,我們可以springboot的啟動log看到如下log信息,即表明我們的ServletContextListener注冊成功。

@SpringBootApplication
@EnableTransactionManagement
@ServletComponentScan
@MapperScan("com.xsxx.mapper")//配置mybatis包掃描
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容