在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!");
    }
}
相关推荐
Counter-Strike大牛3 分钟前
SpringBoot项目调用数据库函数报错Result consisted of more than one row
数据库·spring boot·后端
清汤饺子4 分钟前
Superpowers:给 AI 编程 Agent 装上"工程化超能力"
前端·javascript·后端
念何架构之路14 分钟前
Go语言表达式的求值顺序
开发语言·后端·golang
zihao_tom16 分钟前
Springboot-配置文件中敏感信息的加密:三种加密保护方法比较
java·spring boot·后端
程序员buddha18 分钟前
Java面试八股文框架篇
java·开发语言·面试
毕设源码-钟学长27 分钟前
【开题答辩全过程】以 基于Java的医药进出口交易系统设计与实现为例,包含答辩的问题和答案
java·开发语言
Touch&28 分钟前
Windows11多个JDK版本(Java8、Java11、Java17、Java21)下载安装和切换
java·jdk·jdk多个版本切换
.生产的驴30 分钟前
1Panel实战|SpringColud微服务部署生产环境一键部署Docker+Nacos+MySQL 数据定时备份 控制台 安全高效易维护
服务器·后端·mysql·spring cloud·docker·微服务·信息可视化
帮我吧智能服务平台37 分钟前
装备制造企业售后服务数字化:从成本中心到利润中心背景
java·前端·制造
历程里程碑38 分钟前
Proto3 三大高级类型:Any、Oneof、Map 灵活解决复杂业务场景
java·大数据·开发语言·数据结构·elasticsearch·链表·搜索引擎