springboot 监听器的简单示例

在上家公司,有一次我面试别人时问过一个问题“如果你在web项目启动时,就要做一个操作,删除服务器里面某个硬盘的日志,这些日志是之前留下来的,现在重新启动需要把之前的日志清除,你可以怎么做?”

答案是,可以写一个监听器去做这个操作。

监听器有很多种,本文介绍 servlet上下文监听器 ServletContextListener。

下面给一个入门例子,只需要简单的2部。

(1)用注解@WebListener写一个监听器,继承ServletContextListener。通常在里面的contextInitialized 方法做一些项目启动前的预处理。

@WebListener
public class StartListener implements ServletContextListener{
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("【监听器 StartListener】 contextDestroyed method %%%%%%%%%%%%%%%%");
    }
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("【监听器 StartListener】StartListener contextInitialized method %%%%%%%%%%%%%%");
        System.out.println("在监听器中做一些预处理..........");
    }
}
(2)在启动类加上注解 @ServletComponentScan ,启动类即springboot 中带有main方法的那个启动类。

启动项目,在启动完成前会执行下面2句话:

System.out.println("【监听器 StartListener】StartListener contextInitialized method %%%%%%%%%%%%%%");
System.out.println("在监听器中做一些预处理..........");


猜你喜欢

转载自blog.csdn.net/neymar_jr/article/details/79174303