在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!");
    }
}
相关推荐
亓才孓13 分钟前
[JDBC]批处理
java
春日见14 分钟前
车辆动力学:前后轮车轴
java·开发语言·驱动开发·docker·计算机外设
宋小黑26 分钟前
JDK 6到25 全版本网盘合集 (Windows + Mac + Linux)
java·后端
念何架构之路35 分钟前
Go进阶之panic
开发语言·后端·golang
7哥♡ۣۖᝰꫛꫀꪝۣℋ38 分钟前
Spring-cloud\Eureka
java·spring·微服务·eureka
先跑起来再说38 分钟前
Git 入门到实战:一篇搞懂安装、命令、远程仓库与 IDEA 集成
ide·git·后端·elasticsearch·golang·intellij-idea
老毛肚1 小时前
手写mybatis
java·数据库·mybatis
两点王爷1 小时前
Java基础面试题——【Java语言特性】
java·开发语言
choke2331 小时前
[特殊字符] Python 文件与路径操作
java·前端·javascript
choke2331 小时前
Python 基础语法精讲:数据类型、运算符与输入输出
java·linux·服务器