在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!");
    }
}
相关推荐
喵了几个咪5 分钟前
使用Bazel构建你的Kratos微服务
java·运维·微服务
千寻技术帮30 分钟前
50022_基于微信小程序同城维修系统
java·mysql·微信小程序·小程序·同城维修
野蛮人6号44 分钟前
黑马八股笔记
java
码事漫谈1 小时前
快速入门现代C++:从C++11到C++20的核心特性
后端
Charles_go1 小时前
41、C#什么是单例设计模式
java·设计模式·c#
码事漫谈1 小时前
深入解析进程间通信(IPC)及其应用场景
后端
ejinxian1 小时前
ASP.NET Core 10
后端·asp.net·core 10
皮皮林5511 小时前
别再只会 mvn install 了!深入拆解 Maven 插件核心原理
java·maven
百***49001 小时前
SpringSecurity的配置
java
用户21411832636022 小时前
Claude Skills 硬核技巧:用 PDF-Skill 10 分钟搞定全类型 PDF 自动化,办公人必备
后端