创建项目和配置请移步到: https://blog.csdn.net/weixin_44569835/article/details/108481511
SpringBoot整合Listener有两种: 第一种:通过注解扫描完成 Listener组件的注册 1、编写 Listener
/** * SpringBoot整合Listener方式一 */ @WebListener public class FirstListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("FirstListener...init......"); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }2、编写启动类
/** * SpringBoot整合Listener方式一 */ @SpringBootApplication @ServletComponentScan public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } }3、启动项目测试效果
第二种:通过方法完成 Listener 组件的注册 1、编写 Listener
/** * SpringBoot整合Listener方式二 */ public class SecondListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("SecondListener...init......"); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }2、编写启动类
/** * SpringBoot整合Listener方式二 */ @SpringBootApplication public class App2 { public static void main(String[] args) { SpringApplication.run(App2.class,args); } /** * 注册Listener */ @Bean public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean(){ ServletListenerRegistrationBean<SecondListener> bean = new ServletListenerRegistrationBean<SecondListener>(new SecondListener()); return bean; } }3、启动项目测试效果