ServletContextListener在Springboot中的使用

ServletContextListener是servlet容器中的一个API接口, 它用来监听ServletContext的生命周期,也就是相当于用来监听Web应用的生命周期。今天我们就来说说如何在Springboot 1.5.2这个轻量型框架中如何使用它。
其实配置ServletContextListener与其它Filter, Listener, Servlet方法是一致的,具体可参考Springboot 1.5.2 官方文档
首先写一个类来实现ServletContextListener接口,并实现contextInitialized(), contextDestroyed()两个父类方法,并使用@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 应用启动代码中添加@ServletComponentScan注解,使我们的Springboot应用在启动时能扫描到该Listener.

运行项目,我们可以springboot的启动log看到如下log信息,即表明我们的ServletContextListener注册成功。

@SpringBootApplication
@EnableTransactionManagement
@ServletComponentScan
@MapperScan("com.xsxx.mapper")//配置mybatis包扫描
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容