两种方式:

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

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

1. 编写Listener类

/*** springBoot 整合 Listener 方式一:
 **
 ** 传统方式 一:
 **    <listener>
 **     <listener-class>com.linhw.demo.listener.FirstListener</listener-class>
 ** </listener>
 **/
@WebListener
public class FirstListener implements ServletContextListener{

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

    }
}

2. 编写启动类

@SpringBootApplication
@ServletComponentScan
public class App5 {

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

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

1. 编写Listener类

//与第一种方式的区别,就是没有加@WebListener注解
public class SecondListener implements ServletContextListener{

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

    }
}

2. 编写启动类

@SpringBootApplication
public class App6 {

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

    //添加@Bean将名为"getListener"的bean加入到容器中
    @Bean
    public ServletListenerRegistrationBean<SecondListener> getListener(){
        ServletListenerRegistrationBean<SecondListener> secondLisener = new ServletListenerRegistrationBean<SecondListener>(new SecondListener());
        return secondLisener;
    }
}

最新文章

  1. Apache2.4卡住无法访问的解决……
  2. 检测IE浏览器方法
  3. DEV控件,PopupContainerEdit,PopupContainerControl,TreeList,弹出控制问题
  4. 通过命令行安装Android app
  5. jQuery之渐变切换
  6. 函数flst_get_last
  7. 【C++11】新特性——Lambda函数
  8. 服务器端启动soket多线程
  9. Unity3D基础学习 NGUI自带Tooltip制作提示文字
  10. typeof 使用介绍
  11. IOS引导页的编写
  12. pinyin4j的使用
  13. Hello TensorFlow 三 (Golang)
  14. 15.linux基础
  15. 并发的核心:CAS 是什么?Java8是如何优化 CAS 的?
  16. 目录导航「深入浅出ASP.NET Core系列」
  17. 动态生成table 列
  18. Go语言结构
  19. 线段树入门&amp;lazy思想
  20. windows下docker使用及注意事项

热门文章

  1. FLOPS
  2. array 数组
  3. python--小确幸
  4. hdu 6495 dp
  5. (二十七)golang-排序和查找
  6. win10挂载efi分区
  7. Spring、SpringMVC、Hibernate整合 ----超详细教程
  8. NoSql之Redis系列(.Net Core)
  9. k8s服务器内核参数调整
  10. FastReport的模板文件frx文件啊怎样打开并编辑修改