欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot整合Listener

程序员文章站 2022-05-01 11:34:21
...

原始listener配置

<listener>
	<listener-class>com.tumbler.listener.FirstListener</listener-class>
</listener>

方式一:使用注解扫描完成Listener注册

  1. 创建一个ServletContextListener,添加@WebListener注解
/**
 * User:tumbler
 * Desc:SpringBoot整合Listener方式一:通过注解扫描完成listener注册
 */
@WebListener
public class FirstListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("FirstListener.....init.....");
    }
}
  1. 编写启动类,添加注解@ServletComponentScan
@SpringBootApplication
@ServletComponentScan
public class SpringBootListenerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootListenerApplication.class, args);
    }

}
  1. 启动项目测试,在控制台可见Listener启用
    Spring Boot整合Listener

方式二:使用方法完成Listener注册

  1. 创建SecondListener,不使用注解
/**
 * User:tumbler
 * Desc:SpringBoot整合Listener方式二:通过方法注册Listener
 */
public class SecondListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("SecondListener.....init.....");
    }
}
  1. 编写启动类,在方法上添加@Bean注解注册listener
@SpringBootApplication
public class SpringBootListenerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootListenerApplication.class, args);
    }

    /**
     * 注册Listener
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean<SecondListener> listenerServletListenerRegistrationBean() {
        ServletListenerRegistrationBean<SecondListener> listenerServletListenerRegistrationBean = new ServletListenerRegistrationBean<SecondListener>(new SecondListener());
        return listenerServletListenerRegistrationBean;
    }

}
  1. 启动项目测试
    Spring Boot整合Listener