Spring中的Events事件
简介
Spring中的核心ApplicationContext中的事件处理是通过ApplicationEvent
类和ApplicatoinListener
接口来提供的。这是标准的Observer
模式。
Spring提供的事件类型
ContextRefreshedEvent | 初始化或刷新ApplicationContext时发布(例如,通过使用ConfigurableApplicationContext接口上的refresh()方法)。 |
---|---|
ContextStartedEvent | 通过使用ConfigurableApplicationContext接口上的start()方法启动ApplicationContext时发布。 |
ContextStoppedEvent | 通过使用ConfigurableApplicationContext接口上的stop()方法停止ApplicationContext时发布。 |
ContextClosedEvent | Published 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’sApplicationEventMulticaster
interface.(默认情况下,事件侦听器同步接收事件。这意味着publishEvent()方法将阻塞,直到所有侦听器都已完成对事件的处理。这种同步和单线程方法的一个优点是,当侦听器接收到事件时,如果事务上下文可用,它将在发布者的事务上下文内运行。 如果需要另一个事件发布策略,请参阅Spring的ApplicationEventMulticaster接口的javadoc。)