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

相关推荐
小鹿的周先生1 小时前
Spring AI Chat模型入门——理解 ChatModel、ChatClient、Prompt 和 ChatResponse
人工智能·spring·ai·prompt
霸道流氓气质2 小时前
Spring AI 结构化输出:JSON Mode 与 BeanOutputConverter
人工智能·spring·json
迪飞特科技3 小时前
分布式事务下 Spring 声明式事务失效的 3 种修复方案
分布式·spring·wpf
catino3 小时前
spring-事务@Transactional
java·数据库·spring
Java的搬运工3 小时前
Spring boot 事件监听
java·spring boot·spring·编程语言
小裕哥略帅4 小时前
Spring AOP 实现通用 Token 自动刷新重试工具包
java·后端·spring
凤山老林4 小时前
Spring Boot 3 + Spring Authorization Server 构建企业级 SSO:多端互通、会话共享与
spring boot·后端·spring·单点登录·sso·多端互通
马优晨4 小时前
Spring Servlet 容器是什么、干什么用?
spring·servlet·内嵌servlet容器·java的内嵌servlet·spring内嵌servlet
2601_962073812 天前
Spring全面详解(基础版)
java·后端·spring
凤山老林2 天前
Spring Boot 集成 Spring Vault:集中式密钥管理与动态凭证轮换
spring boot·后端·spring·vault·集中式秘钥管理