Spring Boot(六)自定义事件及监听

本文介绍了Spring框架的事件监听机制,包括自定义事件、监听器的实现方式。详细讲解了编程式监听(实现ApplicationListener接口)、注解式监听(使用@EventListener)以及通过application.properties配置监听器。内容涵盖事件发布、事件接收的源码分析,帮助理解SpringBoot中事件处理的流程。
摘要由CSDN通过智能技术生成

事件及监听并不是SpringBoot的新功能,Spring框架早已提供了完善的事件监听机制,在Spring框架中实现事件监听的流程如下:

  1. 自定义事件,继承org.springframework.context.ApplicationEvent抽象类

  2. 定义事件监听器,实现org.springframework.context.ApplicationListener接口

  3. 在Spring容器中发布事件

实现自定义事件及监听

  • 定义事件
//自定义事件
public class ApplicationEventTest extends ApplicationEvent {
    public ApplicationEventTest(Object source) {
        super(source);
    }
    /**
     * 事件处理事项
     * @param msg
     */
    public void printMsg(String msg)
    {
        System.out.println("监听到事件:"+ApplicationEventTest.class);
    }
}
  • 定义监听器
//自定义事件监听器
//@Component
public class ApplicationListenerTest implements ApplicationListener<ApplicationEventTest> {
    @Override
    public void onApplicationEvent(ApplicationEventTest event) {
        event.printMsg(null);
    }
}
  • 在Spring容器中发布事件
public static void main(String[] args) {
   SpringApplication application = new SpringApplication(SpringbootdemoApplication.class);
   //需要把监听器加入到spring容器中
   application.addListeners(new ApplicationListenerTest());
   Set<ApplicationListener<?>> listeners = application.getListeners();
   ConfigurableApplicationContext context =  application.run(args);
   //发布事件
   context.publishEvent(new ApplicationEventTest(new Object()));
   context.close();
}

上面的示例是在SpringBoot应用中简单的测试一下。

实际开发中实现监听还有其他的方式,在Spring框架中提供了两种事件监听的方式:

  1. 编程式:通过实现ApplicationListener接口来监听指定类型的事件

  2. 注解式:通过在方法上加@EventListener注解的方式监听指定参数类型的事件,写该类需要托管到Spring容器中

 在SpringBoot应用中还可以通过配置的方式实现监听:

   3. 通过application.properties中配置context.listener.classes属性指定监听器

下面分别分析一下这三种监听方式

编程式实现监听

实现ApplicationListenser接口:

@Component
publ
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

仰望星空@脚踏实地

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

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

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

打赏作者

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

抵扣说明:

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

余额充值