在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!");
    }
}
相关推荐
兆子龙1 小时前
ahooks useMemoizedFn:解决 useCallback 的依赖地狱
java·javascript
ん贤3 小时前
Go channel 深入解析
开发语言·后端·golang
曹牧5 小时前
BeanUtils.copyProperties‌
java
changhong19866 小时前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
QWQ___qwq6 小时前
Java线程安全深度总结:基本类型与引用类型的本质区别
java·安全·面试
识君啊6 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
月月玩代码8 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
XPoet9 小时前
AI 编程工程化:Skill——给你的 AI 员工装上技能包
前端·后端·ai编程
阿珍爱上了阿强,在一个有星星的夜晚9 小时前
node后端页面性能监测分析
java·学习方法
Java程序之猿9 小时前
SpringBoot + camel+IBM MQ实现消息队列处理
java·spring boot·mybatis