SpringBoot整合Listener

在传统的web开发时,我们创建一个Listener,需要在web.xml里做配置:

<listener> 
    <listener-class>com.linhw.demo.listener.MyFirstListener</listener-class> 
</listener> 

这样每新增一个Listener类都要在web.xml增加一段类似的配置,很繁琐,降低了开发的效率。

SpringBoot提供了两种方式来解决整个问题:

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

引入依赖:

<!-- 核心启动器, 包括auto-configuration、logging and YAML -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- building web, including RESTful, applications using Spring MVC.
    使用Tomcat作为嵌入式容器, @RestController由这个starter提供-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

@WebListener
public class MyFirstListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //启动时,在控制台可以看到
        System.out.println("MyFirstListener...init......");
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

使用注解的方式必须在SpringBoot启动类增加@ServletComponentScan注解,这样SpringBoot 启动时会扫描@WebListener,实例化这些类。

二、通过方法完成 Listener 组件注册

/**
 * 与第一种方式的区别,就是没有加@WebListener注解
 */
public class MySecondListener implements ServletContextListener {
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //启动时,在控制台可以看到
        System.out.println("MySecondListener Listener...init......");
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        
    }
}

这种方式需要在配置类上以@Bean的形式注入到Spring容器中。

@Configuration
public class BootConfig {

    /**
     * 添加@Bean将名为"getListener"的bean加入到容器中
     */
    @Bean
    public ServletListenerRegistrationBean<MySecondListener> getListener(){
        ServletListenerRegistrationBean<MySecondListener> secondLisener = new ServletListenerRegistrationBean<MySecondListener>(new MySecondListener());
        return secondLisener;
    }
}
原文地址:https://www.cnblogs.com/myitnews/p/12346406.html