事件监听机制
事件监听机制即为设计模式中的观察者模式,包含三个角色,事件、监听者、事件发布者;
- 事件:需要监听的内容;
- 监听器: 监听事件,根据事件内容做相应处理;
- 事件发布者: 包含一个监听者列表,实现对监听器的增删管理,另包含事件发布功能,完成对事件监听者的通知;
java的事件监听机制
事件类EvenObject、事件监听器EventListener,EventPublisher组合事件和监听器实现自定义发布

代码示例
// 事件类
public class Event {
private String message;
public Event(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
// 监听器接口
public interface Listener {
void handleEvent(Event event);
}
//监听器的实现类
// ConsoleListener.java
public class ConsoleListener implements Listener {
public void handleEvent(Event event) {
System.out.println("Received event: " + event.getMessage());
}
}
//事件发布者
import java.util.ArrayList;
import java.util.List;
public class EventPublisher {
private List<Listener> listeners = new ArrayList<Listener>();
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void notify(Event event) {
for (Listener listener : listeners) {
listener.handleEvent(event);
}
}
}
// 测试类,验证事件监听机制
public class Test {
public static void main(String[] args) {
EventPublisher publisher = new EventPublisher();
ConsoleListener listener = new ConsoleListener();
publisher.addListener(listener);
publisher.notify(new Event("Hello world!"));
}
}
spring事件监听机制
- ApplicationEvent: spring容器自定义事件类,继承EventObject,抽象类
- ApplicationListener:自定义事件监听接口,继承自EventListener,ApplicationContext容器在启动时,会自动识别并加载EventListener类型bean定义;
- ApplicationEventPublisher: 事件发布者接口, 完成事件发布,ApplicationContex继承了此接口;
- ApplicacationEventMulticaster: 监听器的注册和和事件发布具体执行者
监听器接口
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
/**
* 处理事件
* @param event the event to respond to
*/
void onApplicationEvent(E event);
/**
* 创建一个新的监听器根据回调接口
* @param consumer the event payload consumer
* @param <T> the type of the event payload
* @return a corresponding {@code ApplicationListener} instance
* @since 5.3
* @see PayloadApplicationEvent
*/
static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
return event -> consumer.accept(event.getPayload());
}
}
事件发布者接口
@FunctionalInterface
public interface ApplicationEventPublisher {
/**
* 通知所有匹配的侦听器处理发布的事件
* @see #publishEvent(Object)
* @see org.springframework.context.event.ContextRefreshedEvent
* @see org.springframework.context.event.ContextClosedEvent
*/
default void publishEvent(ApplicationEvent event) {
publishEvent((Object) event);
}
/**
* 具体实现
* @param event the event to publish
* @since 4.2
* @see #publishEvent(ApplicationEvent)
* @see PayloadApplicationEvent
*/
void publishEvent(Object event);
ApplicacationEventMulticaster接口
public interface ApplicationEventMulticaster {
/**
* Add a listener to be notified of all events.
* @param listener the listener to add
*/
void addApplicationListener(ApplicationListener<?> listener);
/**
* Add a listener bean to be notified of all events.
* @param listenerBeanName the name of the listener bean to add
*/
void addApplicationListenerBean(String listenerBeanName);
/**
* Remove a listener from the notification list.
* @param listener the listener to remove
*/
void removeApplicationListener(ApplicationListener<?> listener);
/**
* Remove a listener bean from the notification list.
* @param listenerBeanName the name of the listener bean to remove
*/
void removeApplicationListenerBean(String listenerBeanName);
/**
* Remove all listeners registered with this multicaster.
* <p>After a remove call, the multicaster will perform no action
* on event notification until new listeners are registered.
*/
void removeAllListeners();
/**
* 发布事件给监听器
* @param event the event to multicast
*/
void multicastEvent(ApplicationEvent event);
/**
* 发布事件给监听器
* @param event the event to multicast
* @param eventType the type of event (can be {@code null})
* @since 4.2
*/
void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType);
}
SimpleApplicationEventMulticaster类
ApplicationEventMulticaster接口默认实现类SimpleApplicationEventMulticaster,

Spring监听机制执行流程
-
AbstractApplicationContext.refresh():刷新容器
-
initApplicationEventMulticaster(): 初始化ApplicationEventMulticaster
- 1、获取beanFactory,
- 2、判断容器内是否有ApplicationEventMulticaster,如有则获取
- 3、如果没有,新建一个SimpleApplicationEventMulticasterv赋值给this.applicationEventMulticaster,并把这个对象注入到容器内
-
registerListeners():注册监听器
- 1、注册静态监听器,
- 2、注册容器内的监听器
- 3、发布早期事件
-
-
AbstractApplicationContext.publishEvent(ApplicationEvent event):事件发布
- 将事件修饰为ApplicationEvent;
- 如果ApplicationEventMulticaster未初始化,则把事件放入earlyApplicationEvents;
- 如果已初始化,则把发布事件;
- 父级容器也进行事件发布操作;
-
SimpleApplicationEventMulticaster 发布事件过程
// 广播事件
@Override
public void multicastEvent(ApplicationEvent event) {
multicastEvent(event, resolveDefaultEventType(event));
}
// 具体执行步骤
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { //事件类型
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
//执行器(线程池)
Executor executor = getTaskExecutor();
//获取事件对应的监听器,并迭代监听器列表,通知监听器执行事件的处理。
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
}
**事件发布步骤**
315

被折叠的 条评论
为什么被折叠?



