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...

相关推荐
小鸡吃米…2 小时前
Python - 类属性
java·前端·python
沉下去,苦磨练!2 小时前
计算一个字符串在另一个字符串中出现次数
java·开发语言
Li_7695322 小时前
Redis —— (五)
java·redis·后端·spring
派大鑫wink2 小时前
【Day7】构造方法与 this 关键字:初始化对象的正确姿势
java·开发语言
JIngJaneIL2 小时前
基于java+ vue办公管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
超级大只老咪3 小时前
速通:类,对象,方法(Java)
java
毕设源码-郭学长3 小时前
【开题答辩全过程】以 基于SpringBoot的企业销售合同管理设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
while(1){yan}3 小时前
JVM八股文
java·开发语言·jvm·java-ee
jiayong233 小时前
Spring AI Alibaba 深度解析(一):框架概述与核心功能
java·人工智能·spring