温馨提示×

温馨提示×

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

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

SpringBoot监听器模式实例分析

发布时间:2022-07-15 13:52:09 来源:亿速云 阅读:175 作者:iii 栏目:开发技术

本篇内容主要讲解“SpringBoot监听器模式实例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot监听器模式实例分析”吧!

1、事件ApplicationEvent

ApplicationEvent是一个抽象类,idea上展开其继承关系如图:

SpringBoot监听器模式实例分析

可见SpringBoot所定义的事件类型是极为丰富的。

2、监听器ApplicationListener

ApplicationListener是一个接口,我们也可以通过实现这个接口来定义自己的监听器,可以通过与事件初始化器方式相似的方式进行加载。

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
	/**
	 * Handle an application event.
	 * @param event the event to respond to
	 */
	void onApplicationEvent(E event);
}

我们可以看到代码中它接受一个上文中提到的事件泛型,这代表了此监听器关注的事件;

还有一种实现监听器的方式,即实现SmartApplicationListener接口,SmartApplicationListener继承了ApplicationListener接口,通过这种方式实现监听器,可以同时注册多个感兴趣的事件,只需实现接口的supportsEventType方法即可;

public interface SmartApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered {
	/**
	 * Determine whether this listener actually supports the given event type.
	 * @param eventType the event type (never {@code null})
	 */
	boolean supportsEventType(Class<? extends ApplicationEvent> eventType);
	/**
	 * Determine whether this listener actually supports the given source type.
	 * <p>The default implementation always returns {@code true}.
	 * @param sourceType the source type, or {@code null} if no source
	 */
	default boolean supportsSourceType(@Nullable Class<?> sourceType) {
		return true;
	}
	/**
	 * Determine this listener's order in a set of listeners for the same event.
	 * <p>The default implementation returns {@link #LOWEST_PRECEDENCE}.
	 */
	@Override
	default int getOrder() {
		return LOWEST_PRECEDENCE;
	}
}

3、事件广播器ApplicationEventMulticaster

ApplicationEventMulticaster是一个接口,定义了添加监听器、删除监听器、传播事件等方法;

SpringBoot为我们实现了SimpleApplicationEventMulticaster这一事件广播器,继承关系如图所示:

SpringBoot监听器模式实例分析

到此,相信大家对“SpringBoot监听器模式实例分析”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

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

AI