在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!");
    }
}
相关推荐
BingoGo1 分钟前
PHP 8.5 将带来什么 🚀
后端
coding随想2 分钟前
查找算法全解析:从顺序查找、折半查找到哈希查找
后端
crud5 分钟前
Spring Boot 使用 @Async 实现异步操作:从入门到实战,一文讲透
java·spring boot
Jooolin6 分钟前
Flask 入门到实战(2):使用 SQLAlchemy 打造可持久化的数据层
后端·flask·ai编程
代码小将15 分钟前
java中static学习笔记
java·笔记·学习
std787917 分钟前
VITA STANDARDS LIST,VITA 最新标准清单大全下载_ansi vita 2025
java·前端·javascript
迢迢星万里灬33 分钟前
Java求职者面试指南:Spring、Spring Boot、MyBatis框架与计算机基础问题解析
java·spring boot·spring·mybatis·计算机基础·面试指南
小远同学35 分钟前
java Mavlink连接模拟器 开源软件Mission Planner简单使用(一)
后端
Jooolin35 分钟前
Flask 入门到实战:手把手带你构建第一个 Python Web 应用
后端·flask·ai编程
烟沙九洲36 分钟前
@Transactional 什么情况下会失效
java·spring