SpringBoot整合Listener

以前编写配置 Listener
<listener>
  <listener-class>com.neuedu.listener.FirstListener</listener-class>
</listener>
SpringBoot 整合Listener方式一

通过注解扫描完成Listener组件的注册

  • 编写Listener
package com.neuedu.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* SpringBoot 整合 Listener 方式一
* 我们这里创建了一个Servlet上下文的监听器,实现ServletContextListener接口即可
* @author 清水三千尺
*
*/
@WebListener
public class FirstListener implements ServletContextListener {
  @Override
  public void contextDestroyed(ServletContextEvent sce) {
      // TODO Auto-generated method stub
  }
  
  @Override
  public void contextInitialized(ServletContextEvent sce) {
      System.out.println("FirstListener...init....");
  }
}
  • 编写启动类
package com.neuedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* SpringBoot 启动类
* @author 清水三千尺
*
*/
@SpringBootApplication
@ServletComponentScan //在SpringBoot启动时会扫描@WebListener,并将该类实例化
public class App {
  public static void main(String[] args) throws Exception {
      SpringApplication.run(App.class, args);
  }
}
  • 启动测试

控制台结果:


SpringBoot 整合Listener方式二

通过方法完成Listener组件的注册

  • 编写Listener
package com.neuedu.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* SpringBoot 整合 Listener 方式二
* @author 清水三千尺
*
*/
public class SecondListener implements ServletContextListener {
  @Override
  public void contextDestroyed(ServletContextEvent sce) {
      // TODO Auto-generated method stub
  }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
      System.out.println("SecondListener...init....");
  }
}
  • 编写启动类
package com.neuedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.neuedu.listener.SecondListener;
/**
* SpringBoot 启动类
* @author 清水三千尺
*
*/
@SpringBootApplication
public class App2 {
  public static void main(String[] args) throws Exception {
      SpringApplication.run(App2.class, args);
  }
  
  /**
   * 注册Listener
   */
  @Bean
  public ServletListenerRegistrationBean<SecondListener> getListenerRegistrationBean() {
      //完成SecondListener的注册
      ServletListenerRegistrationBean<SecondListener> bean = new ServletListenerRegistrationBean<SecondListener>(new SecondListener());
      return bean;
  }
}
  • 启动测试

控制台结果:


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容