SpringBoot 监听器

这篇具有很好参考价值的文章主要介绍了SpringBoot 监听器。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

介绍

Spring的监听器也可以说是一种观察者模式,它能实现事件与事件监听者直接的解耦,在Spring中监听器的实现主要有一下重要组件:

  • ApplicationListener:事件监听者,观察者;
  • ApplicationEvent:Spring 事件,记录事件源、事件内容、时间等数据;
  • 有些场景事件主体主要是String或基本类型,4.2版本之后,不再强制要求继承ApplicationEvent,非ApplicationEvent子类的对象将被包装成PayloadApplicationEvent
  • @EventListener:除了实现ApplicationListener接口注册监听器,也可以使用注解的方式
  • ApplicationEventPublisher:发布事件;

事件监听4种方式

springboot进行事件监听有四种方式:

  1. 手工向ApplicationContext中添加监听器
  2. 使用注解将监听器装载入spring容器
  3. 在application.properties中配置监听器
  4. 通过@EventListener注解实现事件监听

讲到事件监听,这里我们说下自定义事件和自定义监听器类的实现方式:

  • 自定义事件:继承自ApplicationEvent抽象类,然后定义自己的构造器

  • 自定义监听:实现ApplicationListener<T>接口,然后实现onApplicationEvent方法。注意:该接口的实现类必须放到IOC容器中,否者不会起作用。

自定义事件

import org.springframework.context.ApplicationEvent;

/**
 * created at 2023/4/18 10:43
 *
 * @author somnuszpli
 */
public class MyEvent extends ApplicationEvent {

    private Long id;

    private String name;

    public MyEvent(Long id, String name) {
        super(id);
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

发布事件

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

/**
 * created at 2023/4/18 10:52
 *
 * @author somnuszpli
 */
@Component
public class MyEventPublisher {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void publishEvent(Long id, String name) {
        MyEvent event = new MyEvent(id,name);
        applicationEventPublisher.publishEvent(event);
    }
}

1. 手工向ApplicationContext中添加监听器

首先创建MyListener1类

public class MyListener1 implements ApplicationListener<MyEvent>{
	Logger logger = Logger.getLogger(MyListener1.class);
	
	public void onApplicationEvent(MyEvent event){
		logger.info(String.format("%s监听到事件源:%s.", MyListener1.class.getName(), event.getSource()));
	}
}

然后在springboot应用启动类中获取ConfigurableApplicationContext上下文,装载监听

@SpringBootApplication
public class LisenterApplication{
	public static void main(String[] args){
		ConfigurableApplicationContext context = SpringApplication.run(LisenterApplication.class, args);
		//装载监听
		context.addApplicationListener(new MyListener1());
	}
}

2. 使用注解将监听器装载入spring容器

创建MyListener2类,并使用@Component注解将该类装载入spring容器中

@Component
public class MyListener2 implements ApplicationListener<MyEvent>{
	Logger logger = Logger.getLogger(MyListener2.class);
	
	public void onApplicationEvent(MyEvent event){
		logger.info(String.format("%s监听到事件源:%s.", MyListener2.class.getName(), event.getSource()));
	}
}

3. 在application.properties中配置监听器

首先创建MyListener3类

public class MyListener3 implements ApplicationListener<MyEvent>{
	Logger logger = Logger.getLogger(MyListener3.class);
	
	public void onApplicationEvent(MyEvent event){
		logger.info(String.format("%s监听到事件源:%s.", MyListener3.class.getName(), event.getSource()));
	}
}

然后在application.properties中配置监听

context.listener.classes=com.listener.MyListener3

4. 通过@EventListener注解实现事件监听

创建MyListener4类,该类无需实现ApplicationListener接口,使用@EventListener装饰具体方法

@Component
public class MyListener4{
	Logger logger = Logger.getLogger(MyListener4.class);
	
  // @EventListener 注解支持根据Event参数类型进行匹配
	@EventListener
	public void listener(MyEvent event){
		logger.info(String.format("%s监听到事件源:%s.", MyListener4.class.getName(), event.getSource()));
	}
}

PayloadApplicationEvent

有些时候我们事件传递的对象是一些简单的对象,比如一个字符串,不想继承ApplicationEvent对象,可以使用PayloadApplicationEvent

@Component
public class PayloadApplicationListener implements ApplicationListener<PayloadApplicationEvent<String>> {

    @Override
    public void onApplicationEvent(PayloadApplicationEvent<String> event) {
        System.out.println(event.getPayload());
    }
}
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

        //applicationContext.publishEvent(new InitializePost(applicationContext, "Y"));
        applicationContext.publishEvent("hello world");
        //applicationContext.publishEvent(new C());
    }

运行结果文章来源地址https://www.toymoban.com/news/detail-485096.html

hello world

到了这里,关于SpringBoot 监听器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring高手之路15——掌握Spring事件监听器的内部逻辑与实现

    在阅读本文之前需要你已经对事件监听器有了简单的了解,或去阅读前面的文章《 Spring高手之路7——事件机制与监听器的全面探索 》   在 Spring 中, ApplicationContext 可以形成一个层次结构,通常由主容器和多个子容器组成。一个常见的疑问是:当一个事件在其中一个容器

    2024年02月06日
    浏览(36)
  • Spring高手之路7——事件机制与监听器的全面探索

      观察者模式是一种行为设计模式,它定义了对象之间的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。在这个模式中,改变状态的对象被称为主题,依赖的对象被称为观察者。 举个实际的例子: 事件源(Event Source) :可以视

    2024年02月11日
    浏览(31)
  • Spring监听器用法与原理详解(带ApplicationListener模型图)

    相信大家都或多或少知道Spring中的监听器,有些人还能说出它采用了 观察者模式 ,但其实它还用到了 适配器模式 , 工厂模式 等。当然,仍有不少人是完全不了解Spring的监听及其机制的,本次我们就来深入学习一下 Spring监听器 Spring监听器是一种 特殊的类,它们能帮助开发

    2024年02月06日
    浏览(42)
  • Springboot中使用拦截器、过滤器、监听器

    Javaweb三大组件:servlet、Filter(过滤器)、 Listener(监听器) SpringBoot特有组件:Interceptor(拦截器) 过滤器、拦截器、监听器、AOP(后续文章介绍)、全局异常处理器(后续文章介绍)是搭建系统框架时,经常用到的部分,全局异常处理器的作用很明显,就是处理接口执行

    2024年02月03日
    浏览(30)
  • springboot监听器的使用(ApplicationListener、SmartApplicationListener、@EventListener)

    监听器: 当某个事件触发的时候,就会执行的方法块。 springboot提供了两个接口来实现监听: ApplicationListener 、 SmartApplicationListener ,如下图。显而易见, SmartApplicationListener 是 ApplicationListener 的子类,故而其功能要强于 ApplicationListener 。 当然,springboot很贴心地提供了一个

    2024年01月15日
    浏览(28)
  • Flutter中的AppLifecycleListener:应用生命周期监听器介绍及使用

    引言 当你在Flutter中需要监听应用程序的生命周期变化时,可以使用 AppLifecycleListener 。在Flutter 3.13中, AppLifecycleListener 被添加到Framework中,用于监听应用程序的生命周期变化,并响应退出应用程序的请求等支持。 在Flutter 3.13之前,我们通常使用 WidgetsBindingObserver 的 didChange

    2024年01月20日
    浏览(37)
  • Spring项目配置文件中RabbitMQ监听器各个参数的作用

    spring.rabbitmq.listener.simple.concurrency :设置监听器容器的并发消费者数量,默认为1,即单线程消费。 spring.rabbitmq.listener.simple.max-concurrency :设置监听器容器的最大并发消费者数量。 spring.rabbitmq.listener.simple.prefetch :设置每个消费者从RabbitMQ服务器获取的消息数量,即每次从队列

    2024年02月16日
    浏览(26)
  • Spring Boot实战:拦截器和监听器的应用指南

    当使用Spring Boot时,我们可以通过拦截器(Interceptor)和监听器(Listener)来实现对请求和响应的处理。拦截器和监听器提供了一种可插拔的机制,用于在请求处理过程中进行自定义操作,例如记录日志、身份验证、权限检查等。下面通过提供一个示例,展示如何使用拦截器和

    2024年02月09日
    浏览(36)
  • SpringBoot2.0(过滤器,监听器,拦截器)

    使用Servlet3.0的注解进行配置 启动类里面增加 @ServletComponentScan ,进行扫描 新建一个Filter类,implements Filter ,并实现对应接口 @WebFilter 标记一个类为Filter,被spring进行扫描 urlPatterns:拦截规则,支持正则 控制chain.doFilter的方法的调用,来实现是否通过放行, 不放行的话,web应用

    2024年02月07日
    浏览(31)
  • 207、SpringBoot 整合 RabbitMQ 实现消息的发送 与 接收(监听器)

    1、ContentUtil 先定义常量 2、RabbitMQConfig 创建队列的两种方式之一: 配置式: 在容器中配置 org.springframework.amqp.core.Queue 类型的Bean,RabbitMQ将会自动为该Bean创建对应的队列。 就是在配置类中创建一个生成消息队列的@Bean。 问题: 用 @Configuration 注解声明为配置类,但是项目启动

    2024年02月06日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包