Spring只Event事件

Spring中的Events事件

简介

Spring中的核心ApplicationContext中的事件处理是通过ApplicationEvent类和ApplicatoinListener接口来提供的。这是标准的Observer模式。

Spring提供的事件类型

ContextRefreshedEvent初始化或刷新ApplicationContext时发布(例如,通过使用ConfigurableApplicationContext接口上的refresh()方法)。
ContextStartedEvent通过使用ConfigurableApplicationContext接口上的start()方法启动ApplicationContext时发布。
ContextStoppedEvent通过使用ConfigurableApplicationContext接口上的stop()方法停止ApplicationContext时发布。
ContextClosedEventPublished when the ApplicationContext is closed by using the close() method on the ConfigurableApplicationContext interface.
RequestHandledEvent一个特定于Web的事件,告诉所有bean已经为HTTP请求提供服务。请求完成后发布此事件。此事件仅适用于使用Spring的DispatcherServlet的Web应用程序
同步使用

继承或实现的类或接口

  • ApplicationEvent
  • ApplicationEventPublisherAware
  • ApplicationListener

Annotation注解

  • @ApplicationListener
  • ApplicationEventPublisher (@FunctionalInterface)
异步使用

@Async

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

异步发布事件监听注意点

  • 如果事件监听器throws Exception,它不会传播给调用者有关更多详细信息,请参阅AsyncUncaughtExceptionHandler
  • 异步事件事件是不能发送回复信息的。如果您需要作为处理结果发送另一个事件,请注入ApplicationEventPublisher以手动发送事件。
事件顺序

@Order

@EventListener
@Order(42)
public void processBlackListEvent(BlackListEvent event) {
    // notify appropriate parties via notificationAddress...
}
通用事件

可以使用泛型来进一步定义事件的结构。 考虑使用EntityCreatedEvent ,其中T是创建的实际实体的类型。 例如,您可以创建以下侦听器定义以仅接收Person的EntityCreatedEvent。

@EventListener
public void onPersonCreated(EntityCreatedEvent<Person> event) {
    ...
}
项目中的应用
  • 携程Apollo AppController.create();
Spring中的Event事件注意点
  • by default, event listeners receive events synchronously. This means that the publishEvent() method blocks until all listeners have finished processing the event. One advantage of this synchronous and single-threaded approach is that, when a listener receives an event, it operates inside the transaction context of the publisher if a transaction context is available. If another strategy for event publication becomes necessary, See the javadoc for Spring’s ApplicationEventMulticaster interface.(默认情况下,事件侦听器同步接收事件。这意味着publishEvent()方法将阻塞,直到所有侦听器都已完成对事件的处理。这种同步和单线程方法的一个优点是,当侦听器接收到事件时,如果事务上下文可用,它将在发布者的事务上下文内运行。 如果需要另一个事件发布策略,请参阅Spring的ApplicationEventMulticaster接口的javadoc。)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值