06-Spring 中的事件驱动机制
Spring 中的事件驱动机制(ApplicationEvent 源码解析)
本小结主要总结Spring的事件,如果对于观察者模式比较熟悉的话,理解这个应该不难。 这块涉及的面试题相对简单,主要还是以日常使用为主。
另外在Spring的源码中也运用到了大量的事件,如果有大佬想要详细了解的话,小弟也可单独整一篇Spring中的设计模式来一块交流。(当然这个也是Spring面试的重灾区,回答准确明细与否,可能直接关系到技术面试的结果!!)
一、Spring 事件驱动机制概述
Spring 提供了 基于观察者模式的事件驱动机制,用于在应用程序内不同组件之间进行解耦通信。
Spring 的事件驱动机制主要由以下三个核心组件组成:
ApplicationEvent
(事件): 事件的抽象基类,所有自定义事件需要继承该类。ApplicationListener
(监听器): 监听并处理特定类型的事件。ApplicationEventPublisher
(事件发布器): 负责事件的发布,通常由ApplicationContext
充当该角色。
二、Spring 事件驱动机制的基本使用
2.1 自定义事件
public class MyCustomEvent extends ApplicationEvent {
private String message;
public MyCustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
2.2 事件监听器
@Component
public class MyEventListener implements ApplicationListener<MyCustomEvent> {
@Override
public void onApplicationEvent(MyCustomEvent event) {
System.out.println("收到事件:" + event.getMessage());
}
}
2.3 发布事件
@Service
public class EventPublisherService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void publishEvent(String message) {
MyCustomEvent event = new MyCustomEvent(this, message);
eventPublisher.publishEvent(event);
}
}
三、Spring 事件驱动机制源码解析
3.1 事件发布的核心流程
Spring 事件发布的核心流程如下:
- 事件由
ApplicationEventPublisher#publishEvent
方法发布。 - Spring 内部使用
ApplicationEventMulticaster
进行事件广播。 - 事件广播后,符合条件的
ApplicationListener
监听器会被触发,执行onApplicationEvent
方法。
源码解析:ApplicationEventPublisher#publishEvent
@Override
public void publishEvent(ApplicationEvent event) {
this.multicastEvent(event, this.resolveDefaultEventType(event));
}
3.2 事件广播器 ApplicationEventMulticaster
Spring 通过 ApplicationEventMulticaster
来管理事件的广播。
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
for (final ApplicationListener<?> listener : getApplicationListeners(event, eventType)) {
listener.onApplicationEvent(event);
}
}
四、高频面试题
Q1:Spring 事件驱动机制的主要作用是什么?
A1:Spring 事件机制主要用于实现 组件间的松耦合通信,如系统启动事件、用户操作日志记录等。
Q2:如何异步处理事件?
A2:可以使用 @Async
让事件监听器异步执行:
@Component
public class AsyncEventListener {
@Async
@EventListener
public void handleEvent(MyCustomEvent event) {
System.out.println("异步处理事件:" + event.getMessage());
}
}
五、总结
- Spring 事件驱动机制基于观察者模式,实现了组件之间的解耦。
- 事件发布者 通过
ApplicationEventPublisher
触发事件。 - 事件监听器 通过
ApplicationListener
或@EventListener
监听事件。 - 事件广播器 通过
ApplicationEventMulticaster
负责调用监听器。