SpringBoot【整合Listener】

  本文继续介绍SpringBoot整合Listener的步骤

整合Listener

一、整合方式一

1.创建Listener

 &esmp;创建一个自定义的Listener,监听ServletContext的初始化和销毁的行为,具体如下:

/**
 * @program: springboot-01-servlet
 * @description: SpringBoot整合Listener第一种方式
 * @author: 波波烤鸭
 * @create: 2019-05-11 16:01
 */
@WebListener
public class FisrtListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("FirstListener:Servlet容器初始化...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("FirstListener:Servlet容器被销毁了");

    }
}

2.创建启动器

  启动还是和之前一样,没什么区别。

@SpringBootApplication
//在 springBoot 启动时会扫描@WebServlet,并将该类实例化
@ServletComponentScan()
public class Springboot01ServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot01ServletApplication.class, args);
    }

}

3.启动测试

  通过启动类启动程序,观察控制台。

SpringBoot【整合Listener】
自定义的监听器监控到了Servlet容器加载的过程~

二、整合方式二

1.创建Listener

  创建自定义的监听器,不要添加@WebListener注解

/**
 * @program: springboot-01-servlet
 * @description: SpringBoot整个Servlet的第二种方式的启动类
 * @author: 波波烤鸭
 * @create: 2019-05-11 15:04
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }

    /**
     * 注册自定义的监听器
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
        ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
        return bean;
    }
}

2.创建启动器

  创建启动类,同时创建注册Listener的方法,如下

/**
 * @program: springboot-01-servlet
 * @description: SpringBoot整个Servlet的第二种方式的启动类
 * @author: 波波烤鸭
 * @create: 2019-05-11 15:04
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }

    /**
     * 注册自定义的监听器
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
        ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
        return bean;
    }
}

3.启动测试

  启动程序,观察控制台的输出。

SpringBoot【整合Listener】

输出结果看到不光第二个Listener触发了,而且前面的Listener也触发了。搞定~