本文将按照Spring Event 是什么鬼的思路寻找 Spring 源码中与 Spring Event 有关的设计模式实现
初始化-工厂模式
AbstractApplicationContext.java
/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
Mulicater的创建过程就是通过bean 工厂创建,此处使用了工厂模式,BeanFactory 接口定义了 getBean 方法,AbstractBeanFactory 实现了getBean方法,而针对 Bean 的管理( Bean的定义、Bean的创建以及对Bean的解析)AbstractXXXBeanFactory等抽象类来管理,不同的抽象类有不同的管理策略。
事件发布-观察者模式
//AbstractApplicationEventMulticaster.java
public void multicastEvent(final ApplicationEvent event) {
for (final ApplicationListener listener : getApplicationListeners(event)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {
public void run() {
listener.onApplicationEvent(event);
}
});
}
else {
listener.onApplicationEvent(event);
}
}
}
根据 event,找到监听的 listener,在事件触发时,调用 listener 的 onApplicationEvent(event) 方法,此处观察者模式的运用得益于 ApplicationEvent ApplicationListener 两个接口的定义,Spring 通过 Listener 的监听方法参数与实际触发的事件对象匹配来区别是否应该调用Listener的 onApplicationEvent 方法。