SpringBoot如何整合Listener

2023-05-15,

今天就跟大家聊聊有关SpringBoot如何整合Listener,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

SpringBoot 整合 Listener

一.注解方式整合

1. 创建Listener类 实现 ServletContextListener 接口

  • 需要@WebListener 注解

package com.zhl.springbootweb.listener;/** 整合Listener* */import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.annotation.WebListener;@WebListenerpublic class FirstListener implements ServletContextListener {@Override    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("FirstListener init");
    }@Override    public void contextDestroyed(ServletContextEvent sce) {

    }
}

2.启动类需要@ServletComponentScan 注解

@SpringBootApplication/*在SpringBoot启动时会扫描@WebServlet,@WebFilter @WebListener注解,并将该类实例化*/@ServletComponentScanpublic class SpringbootWebApplication {public static void main(String[] args) {
        SpringApplication.run(SpringbootWebApplication.class, args);
    }

}

3.测试

二、方法方式

1.创建Listener对象

/*整合Listener 方式二*/public class SecondListener implements ServletContextListener {@Override    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("SecondListener init");
    }@Override    public void contextDestroyed(ServletContextEvent sce) {

    }
}

2.创建配置类

@Configurationpublic class ListenerConfig {@Bean    public ServletListenerRegistrationBean servletListenerRegistrationBean(){
        ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());return  bean;
    }
}

3.测试 

看完上述内容,你们对SpringBoot如何整合Listener有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注本站行业资讯频道,感谢大家的支持。

《SpringBoot如何整合Listener.doc》

下载本文的Word格式文档,以方便收藏与打印。