在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!");
    }
}
相关推荐
excel2 小时前
基于 GPT 的自动发布文章接口方案:从一句话或一张图片生成并发布内容
前端·javascript·后端
风若飞4 小时前
Spring Ai 入门遇到问题1
java·后端·spring
Nuanyt4 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
AI入职记4 小时前
Spring AI 结构化输出:结构 100% 通过,严格准确率只有 57%
后端·ai编程
aZhe的全栈知识分享4 小时前
AI 还原 Figma 效果总达不到预期?先别急着让它写代码
前端·后端·面试
码事漫谈4 小时前
WorkBuddy 一直更新卡死?两个毛病,一套处理办法
后端
函数小陈4 小时前
阿里云部署DSH与RAM完成运维
前端·后端
aurora_zjj5 小时前
一次持续 3 年的 OpenResty 死循环排查:最终定位到 LuaJIT ARM64 的一条汇编指令
后端
智驭未来掌门人5 小时前
动态平台雷达目标引导系统设计与实现
后端
Bazingga5 小时前
一次Agent超时熔断设计踩过的坑
后端