本文將按照Spring Event 是什麼鬼的思路尋找 Spring 源碼中與 Spring Event 有關的設計模式實現
java
初始化-工廠模式
spring
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等抽象類來管理,不一樣的抽象類有不一樣的管理策略。設計模式
事件發佈-觀察者模式app
//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 方法。this