在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!");
    }
}
相关推荐
Alan_757 分钟前
文件上传接口设计-从单文件到分片上传
后端
newerp7 分钟前
Go语言程序结构 —— 变量、声明与零值机制
后端
SamDeepThinking10 分钟前
现场重构一段代码,展示什么叫「好代码,都在表达自己的意图」
java·后端·程序员
Conan在掘金12 分钟前
ArkTS 进阶之道(16):@Styles 样式复用边界——为啥样式不能当对象返
后端
Conan在掘金21 分钟前
ArkTS 进阶之道(15):@BuilderParam 组件参数化边界——为啥 @Builder 能当参数传
后端
小园子的小菜26 分钟前
Java 并发四大工具类深度解析:CountDownLatch、CyclicBarrier、Semaphore、Exchanger 原理、源码与面试考点
java·开发语言·面试
搭贝低代码28 分钟前
设备管理系统迁移改造:从手工台账到二维码数字化的实践路径
java·低代码·搭贝
前端双越老师30 分钟前
Nest.js 和 Spring Boot 为何如此像?写给前端转 Java 的同学
java·spring boot·全栈
JL1541 分钟前
Java+Go 混合架构怎么搭?收官 50 道面试题 + 学习路线
java·架构·golang
IT_陈寒1 小时前
Redis踩了个大坑,原来DEL命令也会卡住整个实例
前端·人工智能·后端