简介

说明

本文用实例来介绍如何在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自定义事件的资料请关注Devmax其它相关文章!

SpringBoot实现自定义事件的方法详解的更多相关文章

  1. vue自定义加载指令v-loading占位图指令v-showimg

    这篇文章主要为大家介绍了vue自定义加载指令和v-loading占位图指令v-showimg的示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  2. SpringBoot本地磁盘映射问题

    这篇文章主要介绍了SpringBoot本地磁盘映射问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源)

    这篇文章主要介绍了java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源),文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

  4. SpringBoot整合Javamail实现邮件发送的详细过程

    日常开发过程中,我们经常需要使用到邮件发送任务,比方说验证码的发送、日常信息的通知等,下面这篇文章主要给大家介绍了关于SpringBoot整合Javamail实现邮件发送的详细过程,需要的朋友可以参考下

  5. SpringBoot详细讲解视图整合引擎thymeleaf

    这篇文章主要分享了Spring Boot整合使用Thymeleaf,Thymeleaf是新一代的Java模板引擎,类似于Velocity、FreeMarker等传统引擎,关于其更多相关内容,需要的小伙伴可以参考一下

  6. Springboot集成mybatis实现多数据源配置详解流程

    在日常开发中,若遇到多个数据源的需求,怎么办呢?通过springboot集成mybatis实现多数据源配置,简单尝试一下,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  7. JQuery在循环中绑定事件的问题详解

    下面小编就为大家带来一篇JQuery在循环中绑定事件的问题详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  8. element-table如何实现自定义表格排序

    这篇文章主要介绍了element-table如何实现自定义表格排序,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  9. vue如何自定义地址设置@

    这篇文章主要介绍了vue如何自定义地址设置@,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  10. 一篇文章带你了解vue.js的事件循环机制

    这篇文章主要为大家详细介绍了vue.js事件循环机制,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

随机推荐

  1. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  3. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  4. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  5. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  6. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  7. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  8. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  9. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Spring JdbcTemplate执行数据库操作详解

    JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便、友好,效率也不错,这篇文章主要介绍了Spring JdbcTemplate执行数据库操作,需要的朋友可以参考下

返回
顶部