前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >观察者模式与SpringBoot应用

观察者模式与SpringBoot应用

原创
作者头像
code-x
修改2022-08-17 14:39:12
4020
修改2022-08-17 14:39:12
举报
文章被收录于专栏:code-xcode-xcode-x

当对象间存在一对多关系时, 则使用观察者模式(Observer Pattern). 比如, 当一个对象被修改时, 则会自动通知依赖它的对象.

image.png
image.png
优点:
  1. 观察者和被观察者是抽象耦合的
  2. 建立一套触发机制
SpringBoot应用场景

在SpringBoot启动流程中org.springframework.boot.SpringApplication#run(java.lang.String...)这个方法里

	SpringApplicationRunListeners listeners = getRunListeners(args);
	listeners.starting();

SpringBoot加载在spring.factories中预定义的

org.springframework.boot.context.event.EventPublishingRunListener这个类通过其内部定义的事件发布器发布事件

	private final SimpleApplicationEventMulticaster initialMulticaster;.

	@Override
	public void starting() {
		//事件发布器&事件
		this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));
	}

最终在这个org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType)方法进行监听器的执行

    @Override
	public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		Executor executor = getTaskExecutor();
		//getApplicationListeners根据事件和事件类型过滤监听器
		for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			if (executor != null) {
				executor.execute(() -> invokeListener(listener, event));
			}
			else {
				//最终调用监听器的onApplicationEvent方法
				invokeListener(listener, event);
			}
		}
	}

由此, 开发者可以通过spring.factories定义接口实现类, 处理SpringBoot各个生命周期的事件

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 优点:
  • SpringBoot应用场景
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档