在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!");
    }
}
相关推荐
wuqingshun3141596 小时前
什么是责任链模式,一般用在什么场景?
java·责任链模式
江畔柳前堤6 小时前
GO01-Go 语言与主流编程语言深度对比
开发语言·人工智能·后端·微服务·云原生·golang·go
世界哪有真情6 小时前
拿人类意识卡 AI?等于用 bug 验收正式产品
前端·人工智能·后端
:-)6 小时前
算法-归并排序
java·开发语言·数据结构·算法·排序算法
wuqingshun3141597 小时前
说一下消息队列的模型有哪些?
java
fīɡЙtīиɡ ℡8 小时前
布隆过滤器
java
yaoxin5211238 小时前
462. Java 反射 - 获取声明类与封闭类
java·开发语言·python
Csvn9 小时前
Day 3:LIKE 与模式匹配 — 让查询学会"模糊搜索"
后端·sql
Hazenix10 小时前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦10 小时前
GO_复合类型---指针
开发语言·后端·golang