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)、测试

相关推荐
Bs_MoneyMagnet37 分钟前
基于springboot+vue的家居生活商城平台的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring
ly76892 小时前
Spring 事件机制在微服务中实现最终一致性的设计
java·spring·微服务·异步处理·最终一致性·spring事件·事务事件
Bs_MoneyMagnet2 小时前
基于springboot+vue的医院陪诊服务预约平台的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring
青春易逝丶2 小时前
SpringDataJPA
java·spring·hibernate
流烟默2 小时前
xxl-job 接入 Spring 的两种方式:手动装配与自动装配(含 initMethod 双启动踩坑实录)
java·spring·xxl-job
谢亮_vipxieliang3 小时前
ValidX与Maven/Gradle集成配置指南
java·spring boot·spring·maven·hibernate
dadaobusi9 小时前
学习:RV lkvm SBI
java·学习·spring
HEJOO912 小时前
深入理解 Java volatile 关键字:原理、用法与常见误区
java·开发语言·spring
Wang's Blog14 小时前
Java框架快速入门: Spring Security+OAuth2之HTTP请求结构与认证基础
java·spring·http
lisin-lee-cooper16 小时前
简单聊聊 Spring 框架源码
java·后端·spring