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

相关推荐
一只专注api接口开发的技术猿2 小时前
如何处理淘宝 API 的请求限流与数据缓存策略
java·大数据·开发语言·数据库·spring
linyb极客之路5 小时前
告别 OpenFeign!Spring 6 原生 HttpExchange 微服务调用实战指南
spring boot·spring·spring cloud
qq_12498707536 小时前
基于springboot的鸣珮乐器销售网站的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·spring·毕业设计·计算机毕业设计
BullSmall6 小时前
SpringBoot 项目日志规范(企业级标准 + 最佳实践)
java·spring boot·spring
一直都在5726 小时前
SpringBoot:自动配置原理
java·spring boot·spring
电商API_180079052476 小时前
大麦网API实战指南:关键字搜索与详情数据获取全解析
java·大数据·前端·人工智能·spring·网络爬虫
廋到被风吹走7 小时前
【Spring】Spring Cloud 配置中心动态刷新与 @RefreshScope 深度原理
java·spring·spring cloud
while(1){yan}7 小时前
SpringAOP
java·开发语言·spring boot·spring·aop
heartbeat..7 小时前
Spring 全局上下文实现指南:单机→异步→分布式
java·分布式·spring·context
码农幻想梦8 小时前
spring6
spring