在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!");
    }
}
相关推荐
Tony Bai8 小时前
【Go 网络编程全解】06 UDP 数据报编程:速度、不可靠与应用层弥补
开发语言·网络·后端·golang·udp
半夏知半秋8 小时前
lua对象池管理工具剖析
服务器·开发语言·后端·学习·lua
卷福同学8 小时前
【AI绘画】你有多久没有打开SD了?
后端·aigc·ai编程
Moniane8 小时前
时序数据库全面重构指南
java·后端·struts
whm27778 小时前
Visual Basic 值传递与地址传递
java·开发语言·数据结构
没有bug.的程序员9 小时前
云原生与分布式架构的完美融合:从理论到生产实践
java·分布式·微服务·云原生·架构
村口张大爷9 小时前
Spring Boot 初始化钩子
java·spring boot·后端
x_feng_x9 小时前
Java从入门到精通 - 集合框架(二)
java·开发语言·windows
LB21129 小时前
苍穹外卖-缓存套餐 Spring Cache day07
java·spring boot·spring
W.Buffer9 小时前
SpringCloud-Sentinel实战与源码分析:从流量防护到底层实现
spring·spring cloud·sentinel