Spring Boot 自定义 Listener


       在 Spring Boot 之前自定义 Listener 的配置,都是在 webapp/WEB-INF/web.xml 文件下来配置;或者说使用 @WebListener注解的方式来配置。在使用 Spring Boot 开发 Web 项目时,并没有 web.xml 配置文件的存在,所以 Spring Boot 为我们提供了两种方式来将我们自定义的 Listener 注册到 Spring 容器中。

  1. 使用 @WebListener注解方式
  2. 通过 ServletListenerRegistrationBean 类的方式

1.使用 @WebListener注解方式

1.1 自定义 MyListener 类

       自定义一个 MyListener 类,添加注解@WebListener。能监听的Listener有很多,我们在此处监听 ServletContextListener,用来监听 Servlet 启动和销毁。还可以监听HttpSessionListener等,这些 Listener 的父类都是 EventListener。想监听啥,通过 EventListener 查找相对应的实现类来监听就可以了

/**
 * TODO 自定义Listener
 *
 * @author liuzebiao
 * @Date 2020-4-2 15:54
 */
@WebListener
public class MyListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("web应用服务启动");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("web应用服务销毁");
    }
}
1.2 添加 @ServletComponentScan 注解

       在Spring Boot 启动类上,添加一个 @ServletComponentScan 注解

@ServletComponentScan
@SpringBootApplication
public class BootApplication {

    public static void main(String[] args) {
        // Spring应用启动起来         
        SpringApplication.run(BootApplication.class,args);

    }
}

2.编写ServletListenerRegistrationBean 类的方式

2.1 同样先自定义一个 MyListener(代码同1.1中 MyListener,唯一区别是不需要加@WebListener注解)
/**
 * TODO 自定义Listener
 *
 * @author liuzebiao
 * @Date 2020-4-2 15:54
 */
public class MyListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("web应用服务启动");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("web应用服务销毁");
    }
}
2.2 添加 Spring Boot 配置类,将自定义的 MyListener 注册到容器中
@Configuration
public class MyServerConfig {
   //注册MyListener组件
   @Bean
   public ServletListenerRegistrationBean myListener(){
       ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<MyListener>();
       servletListenerRegistrationBean.setListener(new MyListener());
       return servletListenerRegistrationBean;
   }
}

博主写作不易,来个关注呗

求关注、求点赞,加个关注不迷路 ヾ(◍°∇°◍)ノ゙

博主不能保证写的所有知识点都正确,但是能保证纯手敲,错误也请指出,望轻喷 Thanks♪(・ω・)ノ

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扛麻袋的少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值