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; } }
后台打印: