Spring事件监听机制简单使用

简单介绍

Spring的事件监听机制是一个标准的观察者设计模式。它为JavaBean之间提供了消息通信的功能,当一个Bean处理完一个事件后,其他的Bean可以感知到,并进行后续处理。

观察者设计模式:一种行为设计模式, 允许你定义一种订阅机制, 可在对象事件发生时通知多个 "观察" 该对象的其他对象。

其逻辑图如下:

从上图看,当要实现一个Spring事件监听机制,需要三个元素:

  1. 自定义的Event类:它包含事件完成所需要的内容,比如:成员函数、成员变量等。
  2. Publisher:负责使用ApplicationContext发布Event。
  3. Listener:一个或多个监听器,当Publisher发布Event后,其能给监听并执行Listener重定义的onApplicationEvent方法。

Demo实现

第一步:自定义Event类

自定义Event类方法:

  1. 继承ApplicationEvent类
  2. 实现响应的构造函数

代码如下:

java 复制代码
package demo;

import lombok.Getter;
import lombok.Setter;

import org.springframework.context.ApplicationEvent;

@Getter
@Setter
public class DemoEvent extends ApplicationEvent {
    private static final long serialVersionUID = 1L;

    private String message;

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

第二步:实现监听器

实现方法:

  1. 实现ApplicationListener接口
  2. 重写onApplicationEvent方法
  3. 设置@Component注解,将Bean实例化到Spring容器中。(导入 org.springframework.stereotype.Component)

代码如下:

java 复制代码
package demo;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class DemoListenerOne implements ApplicationListener<DemoEvent> {
    @Override
    public void onApplicationEvent(DemoEvent event) {
        System.out.println("DemoListenerOne接收到的消息如下:");
        System.out.println(event.getMessage());
    }
}

按照同样的方式实现再实现DemoListenerTwo监听器。

第三步:发布事件

使用ApplicationContext发布事件,代码如下:

java 复制代码
package demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class DemoPublisher {
    // 容器注入
    @Autowired
    private ApplicationContext context;

    public void send(String msg) {
        // 发布事件
        context.publishEvent(new DemoEvent(this, msg));
    }
}

第四步:测试

java 复制代码
package demo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Date;

public class MainController {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        try {
            DemoPublisher publisher = context.getBean(DemoPublisher.class);
            for (int i = 1; i < 6; i++) {
                publisher.send("发送时间:" + new Date() + ";第" + i + "次发送,请不要回答");
                Thread.sleep(1000);
            }
        } catch (Exception exception) {
            System.out.println(exception.getMessage());
        } finally {
            context.close();
        }
    }
}

执行代码如下:

text 复制代码
DemoListenerOne接收到的消息如下:
发送时间:Mon Dec 22 11:46:25 CST 2025;第1次发送,请不要回答
DemoListenerTwo接收到的消息如下:
发送时间:Mon Dec 22 11:46:25 CST 2025;第1次发送,请不要回答
DemoListenerOne接收到的消息如下:
发送时间:Mon Dec 22 11:46:26 CST 2025;第2次发送,请不要回答
DemoListenerTwo接收到的消息如下:
发送时间:Mon Dec 22 11:46:26 CST 2025;第2次发送,请不要回答
DemoListenerOne接收到的消息如下:
发送时间:Mon Dec 22 11:46:27 CST 2025;第3次发送,请不要回答
DemoListenerTwo接收到的消息如下:
发送时间:Mon Dec 22 11:46:27 CST 2025;第3次发送,请不要回答
DemoListenerOne接收到的消息如下:
发送时间:Mon Dec 22 11:46:28 CST 2025;第4次发送,请不要回答
DemoListenerTwo接收到的消息如下:
发送时间:Mon Dec 22 11:46:28 CST 2025;第4次发送,请不要回答
DemoListenerOne接收到的消息如下:
发送时间:Mon Dec 22 11:46:29 CST 2025;第5次发送,请不要回答
DemoListenerTwo接收到的消息如下:
发送时间:Mon Dec 22 11:46:29 CST 2025;第5次发送,请不要回答

结语

To be continue...

相关推荐
圆山猫6 小时前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
城管不管6 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
IT小白杨7 小时前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡7 小时前
算法日记 - Day3
java·开发语言·算法
萧瑟余晖7 小时前
Java深入解析篇九之NIO详解
java·网络·nio
The Chosen One9858 小时前
高进度算法模板速记(待完善)
java·前端·算法
极光代码工作室10 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
Leighteen10 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
名字还没想好☜11 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
圆山猫11 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v