惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
小众软件
小众软件
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
F
Fortinet All Blogs
T
Tailwind CSS Blog
Martin Fowler
Martin Fowler
I
InfoQ
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
The Cloudflare Blog
罗磊的独立博客

Sunshine

SpringBoot定时任务@Scheduled注解详解 | Sunshine 大端模式、小端模式解析 | Sunshine 机器数、原码、反码、补码解析 | Sunshine IDEA好用的几款插件 | Sunshine Linux使用yum安装MySQL详细步骤(CentOS7.3) | Sunshine Windows下MySQL解压版安装配置详细步骤 | Sunshine Java使用JDBC连接SQLServer数据库(二) | Sunshine Java使用JDBC连接SQLServer数据库(一) | Sunshine Git基本操作整理 | Sunshine Oracle序列创建和使用 | Sunshine Git批量清理本地分支 | Sunshine Statement.RETURN_GENERATED_KEYS获取自增id踩坑记录 | Sunshine GitPages+Hexo搭建个人博客 | Sunshine
Spring事件驱动模型实践 | Sunshine
DongyangHu · 2020-01-09 · via Sunshine

简介

Spring的事件驱动模型,是发布/订阅模式(Publish–subscribe pattern)的实现,或者简单的称之为发布/订阅模式(Publish–subscribe pattern)。主要包括以下几类角色:

  • 事件(ApplicationEvent):需要处理的event本身,继承自Java自身的EventObject
  • 发布者(ApplicationEventPublisher):事件的发布者,用它进行事件的发布
  • 广播(ApplicationEventMulticaster):类似于发布/订阅模式(Publish–subscribe pattern)中Broker的一个概念,负责event存储管理及event的广播
  • 订阅者(ApplicationListener):监听广播出来的不同类别的event

实现

event

1
2
3
4
5
6
public class TestEvent extends ApplicationEvent {

public TestEvent(String message) {
super(message);
}
}

publisher

BasePublisher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component
public class BasePublisher implements ApplicationEventPublisherAware {

private ApplicationEventPublisher applicationEventPublisher;

@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
if (Objects.isNull(this.applicationEventPublisher)) {
this.applicationEventPublisher = applicationEventPublisher;
}
}

public void publish(Object o) {
this.applicationEventPublisher.publishEvent(o);
}
}

TestPublisher

1
2
3
4
5
6
7
8
9
10
11
@Component
public class TestEventPublisher extends BasePublisher {




@PostConstruct
public void init() {
this.publish(new TestEvent("test-message"));
}
}

TestListener

1
2
3
4
5
6
7
8
9
@Slf4j
@Component
public class TestListener implements ApplicationListener<TestEvent> {

@Override
public void onApplicationEvent(TestEvent testEvent) {
log.error("receive event:{}", testEvent.getSource());
}
}

运行结果

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Sunshine