zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    洛谷P2402 奶牛隐藏
    BZOJ2150: 部落战争
    HDU 6405 Make ZYB Happy(广义SAM)
    CodeForces
    2019CCPC秦皇岛 E题 Escape(网络流)
    2019CCPC秦皇岛D题 Decimal
    2019CCPC秦皇岛I题 Invoker(DP)
    2019CCPC秦皇岛 F Forest Program
    2019CCPC秦皇岛 J MUV LUV EXTRA(KMP)
    2019CCPC秦皇岛 K MUV LUV UNLIMITED(博弈)
  • 原文地址:https://www.cnblogs.com/myitnews/p/12346406.html
Copyright © 2011-2022 走看看