Spring的事件机制

  • Spring的事件机制
    • 自定义一个事件
    • 发布一个事件
    • 监听器
    • 深入Spring源码

Spring的事件机制

自定义一个事件

通过继承ApplicationEvent自定义事件

public class BlockedListEvent extends ApplicationEvent {private final String address;private final String content;/*** Create a new {@code ApplicationEvent}.** @param source the object on which the event initially occurred or with*               which the event is associated (never {@code null})* @param address* @param content*/public BlockedListEvent(Object source, String address, String content) {super(source);this.address = address;this.content = content;}
}

发布一个事件

实现ApplicationEventPublisherAware接口通过Spring自带的事件机制发布事件

public class EmailService implements ApplicationEventPublisherAware {private List<String> blockedList;private ApplicationEventPublisher publisher;public void setBlockedList(List<String> blockedList) {this.blockedList = blockedList;}@Overridepublic void setApplicationEventPublisher(ApplicationEventPublisher publisher) {this.publisher = publisher;}public void sendEmail(String address, String content) {if (blockedList.contains(address)) {// 如果给黑名单中的邮件地址发邮件就产生一个事件publisher.publishEvent(new BlockedListEvent(this, address, content));}// send emailSystem.out.println("send email");}

监听器

通过实现ApplicationListener接口实现监听事件

public class BlockedListNotifier implements ApplicationListener<BlockedListEvent> {private String notificationAddress;public void setNotificationAddress(String notificationAddress) {this.notificationAddress = notificationAddress;}@Overridepublic void onApplicationEvent(BlockedListEvent event) {// notify appropriate parties via notificationAddress...System.out.println("onApplicationEvent");}
}

深入Spring源码

protected void registerListeners() {...String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);for (String listenerBeanName : listenerBeanNames) {getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);}...
}protected void publishEvent(Object event, @Nullable ResolvableType eventType) {Assert.notNull(event, "Event must not be null");// Decorate event as an ApplicationEvent if necessaryApplicationEvent applicationEvent;if (event instanceof ApplicationEvent) {applicationEvent = (ApplicationEvent) event;}else {applicationEvent = new PayloadApplicationEvent<>(this, event);if (eventType == null) {eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();}}// Multicast right now if possible - or lazily once the multicaster is initializedif (this.earlyApplicationEvents != null) {this.earlyApplicationEvents.add(applicationEvent);}else {getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);}// Publish event via parent context as well...if (this.parent != null) {if (this.parent instanceof AbstractApplicationContext) {((AbstractApplicationContext) this.parent).publishEvent(event, eventType);}else {this.parent.publishEvent(event);}}}
@Overridepublic void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));Executor executor = getTaskExecutor();for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {if (executor != null) {executor.execute(() -> invokeListener(listener, event));}else {invokeListener(listener, event);}}}

Spring的事件机制相关推荐

  1. spring的事件机制实战

    理论 在分布式场景下,实现同步转异步的方式有三种方式: 1.异步线程池执行:比如借助@Asyn注解,放到spring自带的线程池中去执行: 2.放到消息队列中,在消费者的代码中异步的消费,执行相关的逻 ...

  2. Spring中ApplicationContext的事件机制

    ApplicationContext事件机制是观察者设计模式的实现,通过ApplicationEvent类和ApplicationListener接口,可以实现ApplicationContext事件 ...

  3. Spring事件机制

    一.事件驱动模型简介 事件驱动模型也就是我们常说的观察者,或者发布-订阅模型:理解它的几个关键点: 首先是一种对象间的一对多的关系:最简单的如交通信号灯,信号灯是目标(一方),行人注视着信号灯(多方) ...

  4. Spring高手之路7——事件机制与监听器的全面探索

    文章目录 1. Spring中的观察者模式 2. 监听器 2.1 实现ApplicationListener接口创建监听器 2.2 @EventListener注解创建监听器 2.3 对比Applic ...

  5. Spring 与 Spring Boot 中的事件机制

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 作者 | 温安适 来源 | https://my.osc ...

  6. Spring的事件发布机制

    一:Spring的事件发布 ApplicationContext提供了针对Bean的事件传播功能,其中的主角是publishEvent()方法,通过这个方法可以将事件通知给系统内的监听器(需实现App ...

  7. Spring事件机制详解

    一.前言 说来惭愧,对应Spring事件机制之前只知道实现 ApplicationListener 接口,就可以基于Spring自带的事件做一些事情(如ContextRefreshedEvent),但 ...

  8. spring boot 源码分析(七) 事件机制 之 SpringApplicationEvent

    2019独角兽企业重金招聘Python工程师标准>>> 一.前言 前面的文章我们讲解了一下spring boot配置文件加载的相关源码分析,下面我们将从源码角度讲解一下spring  ...

  9. 框架源码专题:Spring的事件监听、发布机制 ApplicationListener

    文章目录 1.Spring内置事件 2.自定义事件 3.事件监听器 4.事件发布 publishEvent 4.Spring事件原理 5. 面试题:怎么样可以在所有Bean创建完后做扩展代码? 6. ...

最新文章

  1. 前途到底是网络工程还是程序设计
  2. [LUOGU] 1090 合并果子
  3. Android官方技术文档翻译——Gradle 插件用户指南(7)
  4. jpa 动态查询条件 数组_Spring data jpa 复杂动态查询方式总结
  5. ActiveReports报表控件教程之单元格合并
  6. ubuntu下查看进程端口
  7. activiti学习笔记---常见异常
  8. java websocket注解_【websocket】spring boot 集成 websocket 的四种方式
  9. Quartz 定时任务时间表达式说明
  10. hg6201m怎么设置虚拟服务器,移动光猫HG6201M定期重启设置
  11. 为linux下ibus添加五笔98输入法过程详解
  12. word替换妙用小技巧:批量去除多余空格、空行、换行
  13. Git的诞生_繁星漫天_新浪博客
  14. Flask教程(二十)flask-apscheduler
  15. 素材网下载图片要 VIP ? 不存在的
  16. matlab怎么选清浊音做短时谱,语音信号处理实验三
  17. Linux下GPT分区,gdisk修复损坏的分区表
  18. linux系统如何安装mtk驱动程序,模块编译问题 给MTK芯片的wifi网卡编译linux驱动 系统是mint...
  19. 【ESP 保姆级教程】疯狂毕设篇 —— 案例:基于阿里云、小程序、Arduino的温湿度监控系统
  20. 成功解决问题LINK : fatal error LNK1181: 无法打开输入文件“m.lib”error: command ‘D:\\Program Files\\Microsoft Visu

热门文章

  1. mysql重装后出现旧密码_MYSQL重装时需要旧密码解决方法
  2. webrtc audio
  3. Domain Adaptive Video Segmentation viaTemporal Pseudo Supervision
  4. 解决win10 ubuntu双系统删除ubuntu后,windows界面进不去的问题
  5. 读书笔记:《高频交易员》
  6. 【新星计划python赛道】pygame让你一步步实现翻牌游戏(金币旋转、大头贴等),打造更有趣的新星之旅
  7. 用不到1000美元攒一台深度学习用的超快的电脑:继续深度学习和便宜硬件的探奇!...
  8. ddt之读取列表字典,多个字典
  9. windows10 git缓存溢出——不能拉取代码
  10. 如何让图片流动?手把手教你制作