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;
    }
}

 

后台打印:

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM