Spring监听器Listener

news/2025/2/22 6:38:48

目录

1、监听器>Spring监听器简介

2、事件(Event)

3、监听器(Listener)

3、事件发布器

4、监听器使用

4.1、自定义事件

4.2、自定义监听器

4.3、发布事件

4.4、测试

 4.5、使用注解方式监听

4.6、异步事件处理

5、总结


1、监听器>Spring监听器简介

Spring 监听器(Listener)用于监听应用程序中的事件,并在事件发生时执行特定操作。常见的事件包括应用启动、关闭、请求处理等。Spring 提供了多种监听器接口,例如ApplicationListener、ServletRequestListener、HttpSessionListener等,开发者可以通过实现这些接口或者添加对应的注解来监听和处理事件。

2、事件(Event)

在Spring事件顶层类为EventObject抽象类,ApplicationEvent继承了EventObject,是所有事件的基础类,自定义事件需要继承此类。Spring中提供了SpringApplicationEvent,在该类下提供一些实现类。

继承这些类的自定义类都可用作为事件类进行发布,事件通常用于在系统中发生某些操作,通知其他的模块进行一些相应的操作,例如系统启动事件、客户注册系统等。

3、监听器(Listener)

Spring中的监听器ApplicationListener,属于函数式接口,实现该接口的类可用监听特点类型的事件,当检查到特点类型事件时,可用自动进行一些用户开发的操作。

java">@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    void onApplicationEvent(E event);

    default boolean supportsAsyncExecution() {
        return true;
    }

    static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
        return (event) -> {
            consumer.accept(event.getPayload());
        };
    }
}

3、事件发布器

Spring中发布事件的接口ApplicationEventPublisher,用于发布事件。ApplicationContext上下文接口继承了该类,可以发布事件。

java">@FunctionalInterface
public interface ApplicationEventPublisher {
    default void publishEvent(ApplicationEvent event) {
        this.publishEvent((Object)event);
    }

    void publishEvent(Object event);
}

4、监听器使用

4.1、自定义事件

创建自定义事件类,自定义事件类需要继承ApplicationEvent。

java">package com.gs.listener;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent {

    private String message;
    public CustomEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage(){
        return this.message;
    }
}

4.2、自定义监听器

自定义监听器需要实现ApplicationListener接口。

java">package com.gs.listener;

import org.springframework.context.ApplicationListener;

@Component
public class CustomEvenListener implements ApplicationListener<CustomEvent> {
    @Override
    public void onApplicationEvent(CustomEvent event) {
        System.out.println("接受客户消息" + event.getMessage());
    }
}

4.3、发布事件

自定义事件发布器需要实现ApplicationEventPublisher接口

java">package com.gs.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
public class CustomEventPublisher {

    @Autowired
    private ApplicationEventPublisher publisher;
    public void publishCustomEvent(String message){
        System.out.println("发布自定义事件");
        publisher.publishEvent(new CustomEvent(this,"这是一个自定义测试事件"));
    }
}

4.4、测试

java">package com.gs.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CustomEventTest implements CommandLineRunner {

    @Autowired
    private CustomEventPublisher publisher;
    @Override
    public void run(String... args) throws Exception {
        publisher.publishCustomEvent("Hello Spring Event");
    }
}

 运行结果:

 4.5、使用注解方式监听

通过在方法上使用@EventListener注解进行监听

java">package com.gs.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class CustomEvenListener {
    @EventListener
    public void handleCustomEvent(CustomEvent event) {
        System.out.println("接受客户消息: " + event.getMessage());
    }
}

4.6、异步事件处理

默认情况下,Spring事件是同步处理的。如果希望事件处理异步进行,可以使用@Async注解。例如:

java">package com.gs.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class CustomEvenListener {
    @Async
    @EventListener
    public void handleCustomEvent(CustomEvent event) {
        System.out.println("接受客户消息: " + event.getMessage());
    }
}

启动类开启异步:

java">@EnableAsync
@SpringBootApplication
public class DemoProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoProjectApplication.class, args);
    }

}

5、总结

Spring的监听器机制提供了一种灵活的方式来处理应用程序中的事件。通过自定义事件和监听器,可以实现模块之间的解耦,提高代码的可维护性和可扩展性。同时,Spring还提供了注解方式和异步处理的支持,使得事件处理更加方便和高效。


http://www.niftyadmin.cn/n/5861820.html

相关文章

除了Axios,如何用fetch处理403错误?

使用 fetch API 处理 403 错误与使用 Axios 类似&#xff0c;但需要手动检查响应状态。以下是一些最佳实践和示例&#xff0c;展示如何在使用 fetch 时优雅地处理 403 错误。 1. 基本的 Fetch 请求 首先&#xff0c;您需要进行一个基本的 fetch 请求&#xff0c;并检查响应的…

k8s容器运行时环境选型指南

引言 随着云原生技术的普及&#xff0c;Kubernetes已成为容器编排的事实标准&#xff0c;而容器运行时&#xff08;Container Runtime&#xff09;作为其核心底层组件&#xff0c;直接影响着集群的性能、安全性和运维效率。2022年Kubernetes正式弃用Dockershim&#xff0c;标志…

HTTPS 通信流程

HTTPS 通信流程时序图&#xff1a; #mermaid-svg-HWoTbFvfih6aYUu6 {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-HWoTbFvfih6aYUu6 .error-icon{fill:#552222;}#mermaid-svg-HWoTbFvfih6aYUu6 .error-text{fill:#…

消息队列-持续更新中

消息队列 0、消息队列官方参考文档 MQ官方参考文档 RocketMQ 官方文档&#xff1a; https://rocketmq.apache.org/docs/quick-start/ RocketMQ 中国开发者中心&#xff1a;http://rocketmq.cloud/zh-cn/ Kafka 官方文档&#xff1a; http://kafka.apache.org/documentation/ …

伪404兼容huawei生效显示404

根据上述思考&#xff0c;以下是详细的中文分步说明&#xff1a; --- **步骤 1&#xff1a;获取目标设备的User-Agent信息** 首先&#xff0c;我们需要收集目标设备的User-Agent字符串&#xff0c;包括&#xff1a; 1. **iPhone设备的User-Agent**&#xff1a; Mozi…

大数据组件(四)快速入门实时数据湖存储系统Apache Paimon(3)

Paimon的下载及安装&#xff0c;并且了解了主键表的引擎以及changelog-producer的含义参考&#xff1a; 大数据组件(四)快速入门实时数据湖存储系统Apache Paimon(1) 利用Paimon表做lookup join&#xff0c;集成mysql cdc等参考&#xff1a; 大数据组件(四)快速入门实时数据…

电力通信物联网应用,国密网关守护电力数据安全

电力国密网关是用于保护电力调度数据网路由器和电力系统的局域网之间通信安全的电力专用网关机&#xff0c;主要为上下级控制系统之间的广域网通信提供认证与加密服务&#xff0c;实现数据传输的机密性、完整性。 国密算法网关功能特点 身份认证&#xff1a;对接入的设备和用户…

Docker Swarm 内置的集群编排

在现代容器化应用中&#xff0c;容器编排&#xff08;Container Orchestration&#xff09;是至关重要的&#xff0c;它负责自动化容器的部署、扩展、负载均衡和管理。Docker Swarm 是 Docker 提供的原生集群管理和容器编排工具&#xff0c;允许用户通过 Docker CLI 在多个 Doc…