SpringBoot实现自定义事件的方法详解

 更新时间:2022年06月22日 09:03:41   作者:IT利刃出鞘  
这篇文章将用实例来和大家介绍一下如何在SpringBoot中自定义事件来使用观察者模式。文中的示例代码讲解详细,对我们学习SpringBoot有一定的帮助,需要的可以参考一下

简介

说明

本文用实例来介绍如何在SpringBoot中自定义事件来使用观察者模式。

事件的顺序

可使用实现Ordered接口的方式,调整监听器顺序。

注意:必须是同时实现 ApplicationListener<MyEvent>,Ordered这样的方法才能控制顺序。

下边几种都是无法控制顺序的:

  • @Component+@EventListerner+实现Ordered
  • 实现 ApplicationListener<MyEvent>+@Order

步骤1:自定义事件

通过继承ApplicationEvent来自定义事件。

构造器的参数为该事件的相关数据对象,监听器可以获取到该数据对象,进而进行相关逻辑处理。

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

步骤2:自定义监听器

方案1:ApplicationListener

法1:@EventListener

监听单个事件

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
public class MyListener {
    @EventListener
    public void abc(MyEvent event) {
        System.out.println("监听器:     " + "MyListener");
        System.out.println("  线程:     " + Thread.currentThread().getName());
        System.out.println("  事件:     " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
}

或者

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
public class MyListener {
    @EventListener({MyEvent.class})
    public void abc(ApplicationEventevent) {
        System.out.println("监听器:      " + "MyListener");
        System.out.println("  线程:      " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据: " + event.getSource());
    }
}

上边的办法比较好,因为不需要类型转换了。直接就能确定是MyEvent类型。

监听多个事件

事件进来之后,可以使用if(event instanceOf MyEvent.class)来判断是哪种事件。

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener {
    @EventListener({MyEvent.class, MyEvent2.class})
    public void abc(ApplicationEvent event) {
        System.out.println("监听器:      " + "MyListener");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
}

监听所有ApplicationEvent

若使用这种写法,启动时会打印很多Spring自带的事件。任意ApplicationEvent都会进入这里边。

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener {
    @EventListener
    public void abc(ApplicationEvent event) {
        System.out.println("监听器:     " + "MyListener");
        System.out.println("  所在线程: " + Thread.currentThread().getName());
        System.out.println("  事件:     " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
}

法2:实现ApplicationListener<T>接口

public class MyListener implements ApplicationListener<MyEvent>{
 
    public void onApplicationEvent(MyEvent event){
        System.out.println("监听器:     " + "MyListener");
        System.out.println("  所在线程: " + Thread.currentThread().getName());
        System.out.println("  事件:     " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
}

方案2:SmartApplicationListener

源码如下

public interface SmartApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered {
    boolean supportsEventType(Class<? extends ApplicationEvent> var1);
 
    default boolean supportsSourceType(@Nullable Class<?> sourceType) {
        return true;
    }
 
    default int getOrder() {
        return 2147483647;
    }
}

supportsEventType:支持的事件的类型

supportsSourceType:支持的数据的类型

getOrder:2147483641:是2^31-1,也就是32位的int的最大正数 。

示例

事件

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

监听器1

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener implements SmartApplicationListener {
 
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return aClass == MyEvent.class;
    }
 
    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return sourceType == String.class;
    }
 
    @Override
    public int getOrder() {
        return 2;
    }
 
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("监听器:      " + "MyListener");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
        System.out.println("  是MyEvent?:" + (event instanceof MyEvent));
    }
}

监听器2

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener2 implements SmartApplicationListener {
 
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return aClass == MyEvent.class;
    }
 
    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return sourceType == String.class;
    }
 
    @Override
    public int getOrder() {
        return 1;
    }
 
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("监听器:      " + "MyListener2");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
        System.out.println("  是MyEvent?:" + (event instanceof MyEvent));
    }
}

发布器

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        System.out.println("发布器所在线程:" + Thread.currentThread().getName());
        applicationContext.publishEvent(new MyEvent(message));
    }
}

测试

package com.example.controller;
 
import com.example.event.MyPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    MyPublisher myPublisher;
 
    @GetMapping("/test1")
    public String test1() {
        myPublisher.myPublish("Hello");
        return "test1 success";
    }
 
}

启动后,访问:http://localhost:8080/test1

后端输出:

发布器所在线程:http-nio-8080-exec-2
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-2
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
  是MyEvent?:true
监听器:      MyListener
  所在线程:  http-nio-8080-exec-2
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
  是MyEvent?:true

如果将监听器的实现的Ordered顺序颠倒,则输出结果如下:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
  是MyEvent?:true
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
  是MyEvent?:true

步骤3:注册监听器

方式适用范围能否搭配@Async注解,进行异步监听
@Component所有监听器
application.yml中添加配置实现ApplicationListener<T>接口的监听器不能
启动类中注册实现ApplicationListener<T>接口的监听器不能

法1:@Component(适用于所有监听器)

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener {
    @EventListener
    public void abc(MyEvent event) {
        System.out.println("监听器:" + "MyListener");
        System.out.println("线程:" + Thread.currentThread().getName());
        System.out.println("事件:" + event);
        System.out.println("事件的数据:" + event.getSource());
    }
}
package com.example.event;
 
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener2 implements ApplicationListener<MyEvent> {
 
    @Override
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:" + "MyListener2");
        System.out.println("线程:" + Thread.currentThread().getName());
        System.out.println("事件:" + event);
        System.out.println("事件的数据:" + event.getSource());
    }
}

法2:application.yml中添加配置

只适用于实现ApplicationListener<T>接口的监听器

context:
  listener:
    classes: com.example.event.MyListener,com.example.event.MyListener2

法3:启动类中注册

只适用于实现ApplicationListener<T>接口的监听器

package com.example;
 
import com.example.event.MyListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
 
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        // 原来是这样的:SpringApplication.run(DemoApplication.class, args);
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        context.addApplicationListener(new MyListener());
    }
}

步骤4:发布事件

法1:注入ApplicationContext,调用其publishEvent方法

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        applicationContext.publishEvent(new MyEvent(message));
    }
}

法2:启动类中发布

package com.example;
 
import com.example.event.MyEvent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
 
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        //原来是:SpringApplication.run(DemoApplication.class, args);
        ConfigurableApplicationContext context =SpringApplication.run(DemoApplication.class, args);
        context.publishEvent(new MyEvent("Hello"));
    }
}

以上就是SpringBoot实现自定义事件的方法详解的详细内容,更多关于SpringBoot自定义事件的资料请关注脚本之家其它相关文章!

相关文章

  • Java实现MySQL数据实时同步至Elasticsearch的方法详解

    Java实现MySQL数据实时同步至Elasticsearch的方法详解

    MySQL擅长事务处理,而Elasticsearch(ES)则专注于搜索与分析,将MySQL数据实时同步到ES,可以充分发挥两者的优势,下面我们就来看看如何使用Java实现这一功能吧
    2025-03-03
  • java使用poi导出Excel的方法

    java使用poi导出Excel的方法

    这篇文章主要为大家详细介绍了java使用poi导出Excel的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-08-08
  • Spring中Websocket身份验证和授权的实现

    Spring中Websocket身份验证和授权的实现

    在Web应用开发中,安全一直是非常重要的一个方面,本文主要介绍了Spring中Websocket身份验证和授权的实现,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • java char数据类型原理解析

    java char数据类型原理解析

    这篇文章主要介绍了java char数据类型原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • Spring中自动注入的两种方式总结

    Spring中自动注入的两种方式总结

    Spring的核心技术IOC(Intorol of Converse控制反转)的实现途径是DI(dependency Insert依赖注入)。而依赖注入(DI)的实现方式又有两种,xml方式和注解方式。本文就来详细聊聊这两个方式,需要的可以了解一下
    2022-10-10
  • Spring中属性注入详解

    Spring中属性注入详解

    这篇文章主要为大家详细介绍了Spring中属性注入,演示了int、String、数组、list等属性的注入,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • Java多线程编程之读写锁ReadWriteLock用法实例

    Java多线程编程之读写锁ReadWriteLock用法实例

    这篇文章主要介绍了Java多线程编程之读写锁ReadWriteLock用法实例,本文直接给出编码实例,需要的朋友可以参考下
    2015-05-05
  • MyBatis与SpringMVC相结合实现文件上传、下载功能

    MyBatis与SpringMVC相结合实现文件上传、下载功能

    这篇文章主要介绍了MyBatis与SpringMVC相结合实现文件上传、下载功能的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • SpringBoot中application.yml基本配置解读

    SpringBoot中application.yml基本配置解读

    文章主要介绍了Spring Boot项目中`application.properties`和`application.yml`配置文件的使用方法和区别,包括优先级、配置文件所在目录、端口服务配置、数据库配置、多profile配置以及静态资源路径的指定
    2024-12-12
  • springcloud使用profile实现多环境配置方式

    springcloud使用profile实现多环境配置方式

    这篇文章主要介绍了springcloud使用profile实现多环境配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03

最新评论