【Spring | 事件监听详解】

上篇 Spring 事件监听概述 对 Spring 事件监听的机制有了个基本的了解。
本篇来详细的解读下Spring 的 事件监听机制

ApplicationEvent


  ApplicationEvent最重要的子类是ApplicationContextEvent抽象类,ApplicationContextEvent是spring容器Context生命周期事件的基类。

ApplicationContextEvent的有四个子类,如下:

  • ContextRefreshedEvent:当spring容器context刷新时触发
  • ContextStartedEvent:当spring容器context启动后触发
  • ContextStoppedEvent:当spring容器context停止时触发
  • ContextClosedEvent:当spring容器context关闭时触发,容器被关闭时,其管理的所有单例Bean都被销毁。

  以上四个事件就是spring容器生命周期的四个事件,当每个事件触发时,相关的监听器就会监听到相应事件,然后触发onApplicationEvent方法,此时就可以做一些容器,同时这些容器事件跟spring的后置处理器一样,留给用户扩展自定义逻辑,作为暴露的扩展点。

ApplicationEvent 重要的子类关系图如下:
在这里插入图片描述

示例:

public class BlockedListEvent extends ApplicationEvent {

	private final String address;
	private final String content;

	public BlockedListEvent(Object source, String address, String content) {
		super(source);
		this.address = address;
		this.content = content;
	}

	// accessor and other methods...
}

ApplicationListener


  ApplicationListener (继承自JDK的EventListener,JDK要求所有的监听器继承它。)是所有事件监听器的接口,事件监听器监听某个事件必须要实现该接口。
  ApplicationListener 通常使用自定义事件的类型(在前面的示例中为BlockedListEvent)进行参数化。这意味着 onApplicationEvent() 方法可以保持类型安全,避免任何向下转型的需要。您可以根据需要注册任意数量的事件侦听器,但请注意,默认情况下,事件侦听器同步接收事件。这意味着publishEvent()方法将阻塞,直到所有侦听器完成对事件的处理。这种同步单线程方法的优点之一是,当侦听器接收事件时,如果事务上下文可用,它会在发布者的事务上下文内进行操作。若想提供顺序触发监听器的语义,则可以使用另一个接口SmartApplicationListener

public class BlockedListNotifier implements ApplicationListener<BlockedListEvent> {

	private String notificationAddress;

	public void setNotificationAddress(String notificationAddress) {
		this.notificationAddress = notificationAddress;
	}

	public void onApplicationEvent(BlockedListEvent event) {
		// notify appropriate parties via notificationAddress...
	}
}

基于注释


使用`@EventListener` 注释在托管bean 的任何方法上注册事件监听器。重写如下:
public class BlockedListNotifier {

	private String notificationAddress;

	public void setNotificationAddress(String notificationAddress) {
		this.notificationAddress = notificationAddress;
	}

	@EventListener
	public void processBlockedListEvent(BlockedListEvent event) {
		// notify appropriate parties via notificationAddress...
	}
}

方法签名再次声明它所监听的事件类型,但是这一次使用了灵活的名称,并且没有实现特点的监听器接口。只要实际事件类型在它实现的层次结构中解析泛型参数,也可以通过泛型缩小事件类型范围。
也可以在注释本身指定事件类型 ,示例如下:

@EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
public void handleContextStart() {
	// ...
}

还可以通过使用condition 定义表达式的注释的属性SpEL来添加额外的运行时过滤,该表达式应该匹配以实际调用特定事件的方法。
示例如下:

@EventListener(condition = "#blEvent.content == 'my-event'")
public void processBlockedListEvent(BlockedListEvent blEvent) {
	// notify appropriate parties via notificationAddress...
}

SpEL 元数据:

NameDescription
Event实际的ApplicationEvent
Arguments array用于调用该方法的参数(作为对象数组)。
Argument name任何方法参数的名称。如果由于某种原因,名称不可用(例如,因为编译的字节代码中没有调试信息),则也可以使用#a<#arg>的语法来使用各个参数 ,其中<#arg> 代表参数索引(从 0 开始)。

异步


如果您希望特定的监听器异步处理事件,您可以重用 常规@Async 支持。示例如下:

@EventListener
@Async
public void processBlockedListEvent(BlockedListEvent event) {
	// BlockedListEvent is processed in a separate thread
}

使用异步事件时请注意以下限制:

如果异步事件监听器抛出异常,它不会传播到调用者。有关详细信息,请参阅 AsyncUncaughtExceptionHandler

异步事件监听器方法无法通过返回值来发布后续事件。如果您需要发布另一个事件作为处理结果,请注入 ApplicationEventPublisher 来手动发布该事件。

排序


如果您需要在另一个侦听器之前调用一个侦听器,则可以将`@Order` 注释添加到方法声明中,示例如下:
@EventListener
@Order(42)
public void processBlockedListEvent(BlockedListEvent event) {
	// notify appropriate parties via notificationAddress...
}

ApplicationEventMulticaster


ApplicationEventMulticaster接口功能主要用于广播事件给所有监听器,示例如下:
public interface ApplicationEventMulticaster {
    void addApplicationListener(ApplicationListener<?> var1);

    void addApplicationListenerBean(String var1);

    void removeApplicationListener(ApplicationListener<?> var1);

    void removeApplicationListenerBean(String var1);

    void removeAllListeners();

    void multicastEvent(ApplicationEvent var1);

    void multicastEvent(ApplicationEvent var1, @Nullable ResolvableType var2);
}

AbstractApplicationEventMulticasterApplicationEventMulticaster接口的抽象实现,提供监听器的监听器注册的方法。注册监听器时一般不允许相同监听器注册多个实例,因此使用Set集合,用于去重。然后实现广播事件的具体实现没有在这里实现,其他排序子类SimpleApplicationEventMulticaster去实现。

ApplicationEventPublisher


要发布自定义ApplicationEvent,请在ApplicationEventPublisher 上调用 publishEvent() 方法执行。通常,这是通过创建一个实现类 ApplicationEventPublisherAware并将其注册为 Spring bean 来完成的。示例如下:


public class EmailService implements ApplicationEventPublisherAware {

	private List<String> blockedList;
	private ApplicationEventPublisher publisher;

	public void setBlockedList(List<String> blockedList) {
		this.blockedList = blockedList;
	}

	public 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));
			return;
		}
		// send email...
	}
}

在这里插入图片描述

  如果喜欢的话,欢迎 🤞关注 👍点赞 💬评论 🤝收藏  🙌一起讨论
  你的评价就是我✍️创作的动力!					  💞💞💞

参考资料:
Spring-framework 官方文档

  • 35
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 67
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 67
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

家有娇妻张兔兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值