SpringBoot 源码分析 - SpringApplication启动流程四
- 初始化基本流程
- SimpleApplicationEventMulticaster的multicastEvent广播事件
- resolveDefaultEventType获取ResolvableType实例
- ResolvableType的forInstance创建ResolvableType实例
- 开始广播
- AbstractApplicationEventMulticaster的getApplicationListeners获取所有支持该事件的监听器
- DefaultListenerRetriever
- getApplicationListeners直接获取监听器集合
- AbstractApplicationEventMulticaster的retrieveApplicationListeners
初始化基本流程
SimpleApplicationEventMulticaster的multicastEvent广播事件
其实这个就是观察者模式,发布订阅模式,或者说事件驱动模式,如果看过netty就知道他里面的处理器的方法就是事件驱动模式,这里会先进行事件类型解析,解析成ResolvableType
类型。
org.springframework.context.event.SimpleApplicationEventMulticaster
@Overridepublic void multicastEvent(ApplicationEvent event) {multicastEvent(event, resolveDefaultEventType(event));}
resolveDefaultEventType获取ResolvableType实例
private ResolvableType resolveDefaultEventType(ApplicationEvent event) {return ResolvableType.forInstance(event);}
ResolvableType的forInstance创建ResolvableType实例
如果是ResolvableTypeProvider
类型就会获取类型实例返回,否则会创建一个ResolvableType
对象,将事件类型封装进去。
public static ResolvableType forInstance(@Nullable Object instance) {if (instance instanceof ResolvableTypeProvider) {ResolvableType type = ((ResolvableTypeProvider) instance).getResolvableType();if (type != null) {return type;}}return (instance != null ? forClass(instance.getClass()) : NONE);}public static ResolvableType forClass(@Nullable Class<?> clazz) {return new ResolvableType(clazz);//创建一个,把clazz封装进去}
开始广播
获取所有监听器,如果没有执行器就直接调用,有的话会开线程调用,最终都是 invokeListener
。
@Overridepublic 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);}}}
AbstractApplicationEventMulticaster的getApplicationListeners获取所有支持该事件的监听器
现在有个启动事件,但是不一定所有监听器都要支持该事件,如果不支持表示对此事件不关心,那就不需要通知给他了,所以这里就是为了找出支持该事件的监听器集合,找出来之后还会给事件和监听器集合做映射,放入缓存中。
protected Collection<ApplicationListener<?>> getApplicationListeners(ApplicationEvent event, ResolvableType eventType) {//获取事件源,就是事件是谁触发的Object source = event.getSource();Class<?> sourceType = (source != null ? source.getClass() : null);//事件源类型//封装事件类型和事件源类型ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);// 定义一个检索器CachedListenerRetriever newRetriever = null;// 从缓存中获取CachedListenerRetriever existingRetriever = this.retrieverCache.get(cacheKey); //获取监听器检索其if (existingRetriever == null) {// Caching a new ListenerRetriever if possibleif (this.beanClassLoader == null ||(ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) &&(sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) {newRetriever = new CachedListenerRetriever();existingRetriever = this.retrieverCache.putIfAbsent(cacheKey, newRetriever);if (existingRetriever != null) {newRetriever = null; // no need to populate it in retrieveApplicationListeners}}}if (existingRetriever != null) {//获取支持该事件的监听器集合,并放入retriever中Collection<ApplicationListener<?>> result = existingRetriever.getApplicationListeners();if (result != null) {return result;}}//不用缓存的情况,每次都取一遍return retrieveApplicationListeners(eventType, sourceType, newRetriever);}
DefaultListenerRetriever
这个其实就是存监听器的,但是只是对某些事件支持的监听器集合,可以是实例,也可以是 bean
的名字。
private class DefaultListenerRetriever {public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();public final Set<String> applicationListenerBeans = new LinkedHashSet<>();}
getApplicationListeners直接获取监听器集合
直接获取就是将bean
名字的集合里的bean
都实例化,然后跟监听器合并,去重,最后返回
public Collection<ApplicationListener<?>> getApplicationListeners() {List<ApplicationListener<?>> allListeners = new ArrayList<>(this.applicationListeners.size() + this.applicationListenerBeans.size());allListeners.addAll(this.applicationListeners);if (!this.applicationListenerBeans.isEmpty()) {BeanFactory beanFactory = getBeanFactory();for (String listenerBeanName : this.applicationListenerBeans) {try {ApplicationListener<?> listener =beanFactory.getBean(listenerBeanName, ApplicationListener.class);if (!allListeners.contains(listener)) {allListeners.add(listener);}}catch (NoSuchBeanDefinitionException ex) {// Singleton listener instance (without backing bean definition) disappeared -// probably in the middle of the destruction phase}}}AnnotationAwareOrderComparator.sort(allListeners);return allListeners;}
AbstractApplicationEventMulticaster的retrieveApplicationListeners
这个就是根据监听器是否支持该事件,进行监听器的筛选,最后把支持的监听器集合返回。其实还会涉及到bean
名字的集合,支持该事件的会直接获取,然后放进不同的集合里,最后都会讲所有支持的监听器全部返回。这里会把监听器集合也放在ListenerRetriever
里,以便于做事件类型和监听器集合的映射缓存。
private Collection<ApplicationListener<?>> retrieveApplicationListeners(ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable CachedListenerRetriever retriever) {List<ApplicationListener<?>> allListeners = new ArrayList<>();Set<ApplicationListener<?>> filteredListeners = (retriever != null ? new LinkedHashSet<>() : null);Set<String> filteredListenerBeans = (retriever != null ? new LinkedHashSet<>() : null);Set<ApplicationListener<?>> listeners;Set<String> listenerBeans;synchronized (this.defaultRetriever) {//获取SimpleApplicationEventMulticaster添加监听器的时候就加入进去的监听器集合listeners = new LinkedHashSet<>(this.defaultRetriever.applicationListeners);listenerBeans = new LinkedHashSet<>(this.defaultRetriever.applicationListenerBeans);}// Add programmatically registered listeners, including ones coming// from ApplicationListenerDetector (singleton beans and inner beans).for (ApplicationListener<?> listener : listeners) {//遍历所有的监听器,看监听器是否支持该事件if (supportsEvent(listener, eventType, sourceType)) {if (retriever != null) {filteredListeners.add(listener);//支持就添加进去}allListeners.add(listener);//也添加到allListeners里}}// Add listeners by bean name, potentially overlapping with programmatically// registered listeners above - but here potentially with additional metadata.if (!listenerBeans.isEmpty()) {//如果有监听的bean的话,也要加进去ConfigurableBeanFactory beanFactory = getBeanFactory();for (String listenerBeanName : listenerBeans) {try {if (supportsEvent(beanFactory, listenerBeanName, eventType)) {//支持该事件的直接获取ApplicationListener<?> listener =beanFactory.getBean(listenerBeanName, ApplicationListener.class);if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {if (retriever != null) {if (beanFactory.isSingleton(listenerBeanName)) {filteredListeners.add(listener);}else {filteredListenerBeans.add(listenerBeanName);}}allListeners.add(listener);}}else {//不支持就删除// Remove non-matching listeners that originally came from// ApplicationListenerDetector, possibly ruled out by additional// BeanDefinition metadata (e.g. factory method generics) above.Object listener = beanFactory.getSingleton(listenerBeanName);if (retriever != null) {filteredListeners.remove(listener);}allListeners.remove(listener);}}catch (NoSuchBeanDefinitionException ex) {// Singleton listener instance (without backing bean definition) disappeared -// probably in the middle of the destruction phase}}}AnnotationAwareOrderComparator.sort(allListeners);if (retriever != null) {if (filteredListenerBeans.isEmpty()) {retriever.applicationListeners = new LinkedHashSet<>(allListeners);retriever.applicationListenerBeans = filteredListenerBeans;}else {retriever.applicationListeners = filteredListeners;retriever.applicationListenerBeans = filteredListenerBeans;}}return allListeners;}