SpringBoot整合Listener

以前编写配置 Listener

  com.neuedu.listener.FirstListener

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 getListenerRegistrationBean() {
      //完成SecondListener的注册
      ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
      return bean;
  }
}
  • 启动测试

控制台结果:


你可能感兴趣的:(SpringBoot整合Listener)