温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot事件发布和监听的示例分析

发布时间:2022-03-04 11:39:41 来源:亿速云 阅读:146 作者:小新 栏目:开发技术

这篇文章主要介绍SpringBoot事件发布和监听的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

概述

ApplicationEvent以及Listener是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性。事件发布者并不需要考虑谁去监听,监听具体的实现内容是什么,发布者的工作只是为了发布事件而已。事件监听的作用与消息队列有一点类似。

SpringBoot事件发布和监听的示例分析

事件监听的结构

主要有三个部分组成:

  1. 发布者Publisher

  2. 事件Event

  3. 监听者Listener

SpringBoot事件发布和监听的示例分析

Publisher,Event和Listener的关系

SpringBoot事件发布和监听的示例分析

事件

我们自定义事件MyTestEvent继承了ApplicationEvent,继承后必须重载构造函数,构造函数的参数可以任意指定,其中source参数指的是发生事件的对象,一般我们在发布事件时使用的是this关键字代替本类对象,而user参数是我们自定义的注册用户对象,该对象可以在监听内被获取。

@Getter
public class MyTestEvent extends ApplicationEvent {
    private static final long serialVersionUID = 1L;
    private User user;

    public MyTestEvent(Object source, User user) {
        super(source);
        this.user = user;
    }
}

SpringBoot事件发布和监听的示例分析

发布者

事件发布是由ApplicationContext对象管控的,我们发布事件前需要注入ApplicationContext对象调用publishEvent方法完成事件发布。

ApplicationEventPublisher applicationEventPublisher 虽然声明的是ApplicationEventPublisher,但是实际注入的是applicationContext

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    ApplicationEventPublisher applicationEventPublisher;

    @GetMapping("testEvent")
    public void test() {
        applicationEventPublisher.publishEvent(new MyTestEvent("dzf-casfd-111", new User("dzf-625096527-111", "xiaoming", 19)));
        applicationEventPublisher.publishEvent(new MyTestEvent("dzf-49687489-111", new User("dzf-625096527-111", "xiaowang", 20)));
    }


}

监听者

面向接口编程,实现ApplicationListener接口

@Component
public class MyTestListener implements ApplicationListener<MyTestEvent> {

    @Override
    public void onApplicationEvent(MyTestEvent myTestEvent) {
        System.out.println("MyTestListener : " + myTestEvent.getUser());
    }
}

使用@EventListener注解配置

@Component
public class MyTestListener2{

    @EventListener(MyTestEvent.class)
    public void onApplicationEvent(MyTestEvent myTestEvent) {
        System.out.println("MyTestListener2:" + myTestEvent.getUser());
    }
}

以上是“SpringBoot事件发布和监听的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI