当我们借助 Spring 发送一个事件对象的时候,一般都通过 ApplicationEventPublisher 完成,在默认情况下,通过容器获得的 ApplicationEventPublisher 单例实际上就是 ApplicationContext 本身。
ApplicationEventPublisher 提供了两个 publishEvent 方法,一个用于发布 ApplicationEvent 事件,另一个用于发布其他事件,在 AbstractApplicationContext 中,它们都通过同一个私有方法实现:
// 推送ApplicationEvent事件
@Override
public void publishEvent(ApplicationEvent event) {publishEvent(event, null);
}
// 推送非ApplicationEvent事件
@Override
public void publishEvent(Object event) {publishEvent(event, null);
}protected void publishEvent(Object event, @Nullable ResolvableType eventType) {Assert.notNull(event, "Event must not be null");// 如果事件对象没继承ApplicationEvent,就包装为PayloadApplicationEventApplicationEven