在spring中发布订阅事件

Spring 事件机制允许在应用程序中不同的组件之间进行松耦合的通信。下面是一个简单的例子,展示如何在 Spring 中使用事件机制。

java 复制代码
import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent {
    private String message;

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

    public String getMessage() {
        return message;
    }
}
java 复制代码
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {

    @Override
    public void onApplicationEvent(CustomEvent event) {
        System.out.println("Received custom event - " + event.getMessage());
    }
}
java 复制代码
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

@Component
public class CustomEventPublisher implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher eventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher 
    	applicationEventPublisher) {
        this.eventPublisher = applicationEventPublisher;
    }

    public void publishEvent(String message) {
        CustomEvent customEvent = new CustomEvent(this, message);
        eventPublisher.publishEvent(customEvent);
    }
}
java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class EventDemo {

    private final CustomEventPublisher customEventPublisher;

    @Autowired
    public EventDemo(CustomEventPublisher customEventPublisher) {
        this.customEventPublisher = customEventPublisher;
    }

    public void run() {
        customEventPublisher.publishEvent("Hello, Spring Event!");
    }
}
相关推荐
码事漫谈1 小时前
# 2027年,AI终于要开始“干活”了
后端
小满zs2 小时前
Go语言第二十一章(Gin上传文件)
后端·go
皮皮林5512 小时前
为什么越来越多人用 Spring AI ?
spring
兴趣互联3 小时前
jeecgboot nacos2.3.2 使用pgsql
java
hudd6683 小时前
JavaEE 初阶 - 文件操作和IO
java·开发语言·java-ee
JavaGuide4 小时前
Cloudflare 开源的这套神级安全审计 Skill 太好用了!
前端·后端
Flynn Liang4 小时前
HikariCP 连接池不是越大越好:I/O 密集型 Java 服务的数据库容量工程
java·数据库·mysql·高并发·连接池·hikaricp·sql 优化
学长毕设4 小时前
基于SpringBoot社区快递驿站物流配送系统-附源码
java·spring boot·后端
Flynt5 小时前
Java4Shell 实测:EPYC 一跑就中招,关掉 Base64 硬件加速,1KB 解码慢 14 倍
java·安全·性能优化
Resean02235 小时前
Spring 源码分析(七)AOP 原理(上):代理的创建
java·后端·spring