在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!");
    }
}
相关推荐
用户83562907805117 分钟前
使用 Python 在 Excel 中添加和编辑形状
后端·python
用户2049375549520 分钟前
端侧语音部署踩坑:模型能跑不等于终端真的能用
后端·算法
n8n28 分钟前
Spring AI 结构化输出实战:让模型返回 JSON,而非自由文本
后端
Wang's Blog29 分钟前
Java框架快速入门: Spring Security+OAuth2之密码验证规则与自定义注解
java·数据库·spring
一嘴一个橘子36 分钟前
java - redis 缓存击穿 - 互斥锁
java
shehuiyuelaiyuehao41 分钟前
算法39,位运算,消失的两个数字
java·数据结构·算法
小刘在重生~43 分钟前
Java 异常体系完整笔记
java·笔记·python
用户8356290780511 小时前
使用 Python 为 PDF 添加和管理超链接
后端·python
抠脚小弟1 小时前
Spring Task 定时任务详解:从入门到实战
java·后端·spring