当前位置:首页JavaApplicationEvent 使用指南

ApplicationEvent 使用指南

ApplicationEvent 是 Spring 框架中事件驱动编程模型的核心组件,用于实现应用程序内部的事件发布-订阅机制。

ApplicationEvent 是 Spring 框架中事件驱动编程模型的核心组件,用于实现应用程序内部的事件发布-订阅机制。

一、ApplicationEvent 是什么?

ApplicationEvent 是 Spring 的事件抽象类,属于观察者模式在 Spring 中的实现,主要特点包括:

  1. 事件源:事件的产生者
  2. 事件对象:继承 ApplicationEvent 的具体事件类
  3. 监听器:实现 ApplicationListener 或使用 @EventListener
  4. 发布器:ApplicationEventPublisher

二、基本使用方式

1️⃣自定义事件

import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {

    private String message;

    public MyEvent(Object source,String message) {
        super(source);
        this.message = message;
    }

    public String getMessage(){
        return this.message;
    }

2️⃣发布事件

@Service
@RequiredArgsConstructor
public class EventPublisherService {

    private final ApplicationEventPublisher applicationEventPublisher;

    //@Scheduled(fixedDelay = 10 * 1000)  定时测试发布可删
    public void publishEvent() {
        MyEvent hello = new MyEvent(this, "hello");
        applicationEventPublisher.publishEvent(hello);
    }


}

3️⃣监听

@Component
public class MyListener {

    @EventListener
    public void handleMyCustomEvent(MyEvent myEvent) {
        System.out.println(myEvent.getMessage());
    }

}

给TA打赏
共{{data.count}}人
人已打赏
Java

Java如何爬虫获取各省行政区划

2025-3-26 16:46:45

前端笔记

初始化创建Vue工程的3种方法

2022-8-31 15:05:24

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
购物车
优惠劵
有新私信 私信列表
搜索