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

相关推荐
秋千码途12 分钟前
小架构step系列27:Hibernate提供的validator
java·spring·架构·hibernate
探索java14 分钟前
深入理解 Spring 中的 XmlBeanFactory 原理及实践
java·spring·xmlbeanfactory
奋进的孤狼17 分钟前
【Spring AI】阿里云DashScope灵积模型
人工智能·spring·阿里云·ai·云计算
武子康7 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
心之语歌11 小时前
Spring AI MCP 客户端
人工智能·spring·github
Edingbrugh.南空11 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
EmpressBoost17 小时前
谷粒商城170缓存序列化报错
java·spring·缓存
fouryears_2341717 小时前
@PathVariable与@RequestParam的区别
java·spring·mvc·springboot
萌新小白的逆袭17 小时前
《Maven 核心基础笔记(第一天)》
java·开发语言·spring
秋千码途18 小时前
小架构step系列26:Spring提供的validator
java·spring·架构