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

推荐订阅源

Y
Y Combinator Blog
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
Recent Announcements
Recent Announcements
A
About on SuperTechFans
U
Unit 42
MyScale Blog
MyScale Blog
J
Java Code Geeks
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
D
Docker
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 司徒正美
量子位
月光博客
月光博客
G
Google Developers Blog
V
V2EX
博客园 - 聂微东
宝玉的分享
宝玉的分享
IT之家
IT之家
Vercel News
Vercel News

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