Spring 事件监听

参考:Spring事件监听流程分析【源码浅析】_private void processbean(final string beanname, fi-CSDN博客

一、简介

Spring早期通过实现ApplicationListener接口定义监听事件,Spring 4.2开始通过@EventListener注解实现监听事件

复制代码
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);


    /**
     * Create a new {@code ApplicationListener} for the given payload consumer.
     * @param consumer the event payload consumer
     * @param <T> the type of the event payload
     * @return a corresponding {@code ApplicationListener} instance
     * @since 5.3
     * @see PayloadApplicationEvent
     */
    static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
       return event -> consumer.accept(event.getPayload());
    }


}

二、示例

(1)、自定义事件,相当于抽象观察者

复制代码
/*
* 系统日志事件,观察者
* */
public class SysLogEvent extends ApplicationEvent {
    public SysLogEvent(SysLog sysLog){
        super(sysLog);
    }
}

(2)、自定义实现,相当于具体观察者

复制代码
@Component
public class SysLogListener implements ApplicationListener<SysLogEvent> {
    private final static Logger logger = LoggerFactory.getLogger(SysLogListener.class);

    @Override
    public void onApplicationEvent(SysLogEvent event) {
        logger.info("收到调用日志消息:"+ JSON.toJSONString(event));
    }

    /*
    * spring 4.2版本用@EventListener注解
    * */
//    @EventListener(SysLogEvent.class)
    public void saveSysLog(SysLog event){
        logger.info("收到调用日志消息:"+ JSON.toJSON(event));
    }
}

(3)、发布订阅事件

复制代码
@RestController
@RequestMapping("/event")
public class EventController {

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("public")
    public void event(){
       SysLog sysLog = new SysLog();
       sysLog.setLogId("1");
       sysLog.setCode("2");
       sysLog.setMessage("3");
       applicationContext.publishEvent(new SysLogEvent(sysLog));

    }
}

(4)、测试

相关推荐
带刺的坐椅7 分钟前
Java 流程编排新范式 Solon Flow:一个引擎,七种节点,覆盖规则/任务/工作流/AI 编排全场景
java·spring·ai·solon·flow
xiaoshuaishuai843 分钟前
C# CDN加速与离线包优化PowerSetting慢问题
开发语言·windows·spring·c#
野生技术架构师2 小时前
2026最新Java面试八股文天花板(含详细解析)
java·jvm·spring
小小工匠2 小时前
Spring AI RAG - 06 敏感词过滤与内容安全防护
人工智能·安全·spring
接着奏乐接着舞3 小时前
spring cloud知识点
后端·spring·spring cloud
Volunteer Technology3 小时前
Spring AI MCP 案例-WebFlux SSE传输模式 (九)
java·数据库·人工智能·spring
小小工匠4 小时前
Spring AI RAG - 09 AI 绘图 ImageModel 集成
人工智能·spring
青云计划5 小时前
SpringSecurity技术文档
spring
Ting-yu5 小时前
Spring AI Alibaba零基础速成(1) ---- 项目创建与配置
java·人工智能·spring
架构源启6 小时前
Spring AI完整学习路线:从Java开发到AI Agent的进阶之路(附15篇实战教程)
java·人工智能·spring