在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!");
    }
}
相关推荐
辣椒HTTP7 小时前
代理池健康检查与TLS指纹伪装实践
后端
玛卡巴卡ldf7 小时前
【LeetCode 手撕算法】(栈)有效括号、最小栈、字符串解码、每日温度、柱状图最大矩形
java·数据结构·算法·leetcode·力扣
ClouGence7 小时前
豆包收费之后,我找到了更好用的 AI 工具
前端·人工智能·后端·ai·ai编程·ai写作
aircrushin7 小时前
音乐节结束前,拿手机📱搓了一个工具
前端·后端
小撒的私房菜7 小时前
Day 3:多工具时代,Agent 自己选——加入计算器和时间工具
人工智能·后端
czlczl200209257 小时前
MySQL 基于 GTID 的 Binlog 主从同步机制
java·jvm·mysql
Sylvia33.8 小时前
足球数据API接入实战:从认证到实时比分推送的完整指南
java·开发语言·前端·c++·python
Chloeis Syntax8 小时前
JavaEE初阶学习日记(1)---线程和进程
java·开发语言·学习·线程·javaee
YOU OU8 小时前
SpringBoot
java·spring boot·spring
北冥有鱼8 小时前
解决DTO泛滥的问题
java·java ee