在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!");
    }
}
相关推荐
coderCN2 分钟前
HTTP(动静分离)
后端
jj_ccwgw4 分钟前
Kafka 集群开机自启动配置指南
后端·kafka
谢亮_vipxieliang8 分钟前
手机号验证技术方案:号段规则与正则表达式
java·服务器·spring boot·正则表达式·hibernate
wang090720 分钟前
自己动手写一个tomcat之7监听器和过滤器
java·tomcat
梅孔立20 分钟前
Pi-Agent 终极极简配置文档(Java+Vue+Python爬虫 4-5千文件项目)
java·vue.js·python
爱码猿27 分钟前
SpringAop通过el表达式动态获取方法入参的值
spring boot·spring·aop
AskHarries29 分钟前
外链到底还有没有用
后端
Query*33 分钟前
Agent 开发之项目 AI Native 化:通过大模型与 RAG 赋予产品智能能力
java·人工智能·ai
孫治AllenSun33 分钟前
【LangChain4J-03】Springboot 项目搭建框架
java·spring boot·后端
君顾134 分钟前
AI新零售线上商城系统实战:架构设计与开发全流程指南
java·开发语言·零售