【SpringBoot】05.SpringBoot整合Listener的两种方式

SpringBoot整合Listener的两种方式:

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

  1. 创建一个类实现ServletContextListener (具体实现哪个Listener根据情况来判断)
  2. 在类上加入注解@WebListener
  3. 重写contextInitialized()contextDestroyed()方法
  4. 编写启动类
  5. 增加注解@ServletComponentScan
@WebListener
public class FirstListener implements ServletContextListener {
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("Listener...init....");
	}
}
@SpringBootApplication
@ServletComponentScan
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class,args);
	}
}

2.通过方法完成Listener组件注册

  1. 创建一个类实现ServletContextListener (具体实现哪个Listener根据情况来判断)
  2. 编写启动类
  3. 新增方法,方法类型为ServletListenerRegistrationBean<需要注册的Listener的类>
  4. 实例化ServletListenerRegistrationBean对象,构造时传入"需要注册的Listener的类"对象
  5. 返回该对象
  6. 该方法上加注解@Bean
@SpringBootApplication
public class App2 {
	public static void main(String[] args) {
		SpringApplication.run(App2.class, args);
	}
	
	/**
	   * 用于注册Listener
	 */
	@Bean
	public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean(){
		ServletListenerRegistrationBean<SecondListener> srb = new ServletListenerRegistrationBean<SecondListener>(new SecondListener());
		return srb;
	}
}
posted @ 2020-08-19 11:12  邓晓晖  阅读(499)  评论(0编辑  收藏  举报