SpringBoot - 使用Listener

1、在SpringBoot中使用Listener

1.1、使用注解注册Listener:

/**
 * SpringBoot使用 Listener
 */
@WebListener
public class OneListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("OneListener init ...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}

 

@SpringBootApplication
//在 springBoot 启动时会扫描@WebListener并实例化
@ServletComponentScan
public class OneListenerApp {
    public static void main(String[] args) {
        SpringApplication.run(OneListenerApp.class, args);
    }
}

 

后台打印:

 

 

1.2、另一种初始化Filter的方法:方法注册

/**
 * SpringBoot使用 Listener
 */
public class TwoListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("TwoListener init ...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

 

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

    @Bean
    public ServletListenerRegistrationBean registrationListenerBean(){
        ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new TwoListener());
        return bean;
    }
}

 

后台打印:

 

 

posted @ 2018-10-06 20:02  Simple°  阅读(2669)  评论(0编辑  收藏  举报