Spring 5 ApplicationContext#refresh() -- 深入源码解析(二)

相关源码注释

ApplicationContext

Spring 5 DefaultResourceLoader 源码注释
Spring 5 AbstractApplicationContext 源码注释

BeanFactory

Spring 5 SimpleAliasRegistry 源码注释
Spring 5 DefaultSingletonBeanRegistry 源码注释
Spring 5 FactoryBeanRegistrySupport 源码注释
Spring 5 AbstractBeanFactory 源码注释
Spring 5 AbstractAutowireCapableBeanFactory 源码注释
Spring 5 DefaultLisbaleBeanFactory 源码注释

Spring 5 ApplicationContext#refresh() – 深入源码解析(一)
Spring 5 ApplicationContext#refresh() – 深入源码解析(二)

initApplicationEventMulticaster()

/**
	 * Initialize the ApplicationEventMulticaster.
	 * <p>初始化ApplicationEventMulticaster</p>
	 * Uses SimpleApplicationEventMulticaster if none defined in the context.
	 * <p>如果上下文中没有定义,则使用SimpleApplicatioonEventMulticaster</p>
	 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
	 */
protected void initApplicationEventMulticaster() {
    
    
		//获取当前上下文的BeanFactory对象
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		//如果本地BeanFactory包含 applicationEventMulticaster 的bean,忽略父工厂
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
    
    
			//从beanFactory中获取名为 'applicationEventMulticaster' 的 ApplicationEventMulticaster 类型的Bean对象
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			//如果当前是跟踪日志级别
			if (logger.isTraceEnabled()) {
    
    
				//跟踪日志:使用 ApplicationEventMulticaster [applicationEventMulticaster]
				logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}
		else {
    
    //本地BeanFactory没有applicationEventMulticaster的bean对象时
			//SimpleApplicationEventMulticaster:简单实现的 ApplicationEventMulticaster 接口;将所有事件多播给所有注册的监听
			// 	器,让监听器忽略它们不感兴趣的事件。监听器通常 会对传入的事件对象执行相应的 instanceof 检查
			//新建一个 SimpleApplicationEventMulticaster 对象
			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
			//将 applicationEventMulticaster 与 'applicationEventMulticaster' 注册到 beanFactory 中
			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
			//如果当前是跟踪日志级别
			if (logger.isTraceEnabled()) {
    
    
				没有名为'applicationEventMulticaster'的对象,使用 applicationEventMulticaster
				logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
						"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
			}
		}
	}

从beanFactory中获取名为 ‘applicationEventMulticaster’ 的 ApplicationEventMulticaster 类型的Bean对象,引用到 该上下文的 applicationEventMulticaster 属性,如果获取不到,就新建一个 SimpleApplicationEventMulticaster 实例 引用 到 上下文的 applicationEventMulticaster 属性 中

Spring 5 SimpleApplicationEventMulticaster 源码分析

onRefresh();

/**
	 * Template method which can be overridden to add context-specific refresh work.
	 * Called on initialization of special beans, before instantiation of singletons.
	 * <p>模板方法,可以重写该方法以添加特定上下文的刷新工作。在实例化单例对象之前,对特殊Bean进行
	 * 初始化时调用。</p>
	 * <p>This implementation is empty.
	 * <p>这个实现时空的。</p>
	 * @throws BeansException in case of errors -- 以防出现错误
	 * @see #refresh()
	 */
	protected void onRefresh() throws BeansException {
    
    
		// For subclasses: do nothing by default.
		// 对于子类:默认不做任何事情
	}

这里仅分析SpringBoot所用到的 GenericApplicationContext 实现

	/**
	 * Initialize the theme capability.
	 * <p>初始化 主题 功能</p>
	 */
	@Override
	protected void onRefresh() {
    
    
		//初始化给定应用程序上下文的 ThemeSource,自动检查名为 'ThemeSource'的 bean。如果没有找到这样的Bean,将使用默认的'空'主题源
		this.themeSource = UiApplicationContextUtils.initThemeSource(this);
	}

Spring 5 UiApplicationContextUtils 源码分析

registerListeners()

/**
	 * Add beans that implement ApplicationListener as listeners.
	 * Doesn't affect other listeners, which can be added without being beans.
	 * <p>添加将 ApplicationListener 实现为 监听器 的Bean。不会影响其他 监听器,可以在不使用
	 * Bean 的情况下添加其他监听器</p>
	 */
	protected void registerListeners() {
    
    
		// Register statically specified listeners first.
		// 首先注册静态指定的监听器
		//遍历 静态指定的 applicationListener 列表
		for (ApplicationListener<?> listener : getApplicationListeners()) {
    
    
			//获取上下文使用的内部 ApplicationEventMulticater,往里面添加 listener
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let post-processors apply to them!
		// 不要这里初始化FactoryBean:我们需要保持所有常规bean未初始化,以便让BeanPostProcessor应用它们
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		// 遍历listenerBeanNames
		for (String listenerBeanName : listenerBeanNames) {
    
    
			//获取上下文使用的内部 ApplicationEventMulticater,往里面添加一个监听器bean来通知所有事件
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

		// Publish early application events now that we finally have a multicaster...
		// 发布早期的应用事件,现在我们终于有了一个多播器
		//在多播程序设置之前发布的ApplicationEvent集
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		//将earlyApplicationEvents设置为null,因为要保证一个事件只会多播一次。
		this.earlyApplicationEvents = null;
		//如果 earlyEventsToProcess 不为 null
		if (earlyEventsToProcess != null) {
    
    
			//遍历 earlyEventsToProcess
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
    
    
				//获取上下文使用的内部 ApplicationEventMulticater,多播earlyEvent到适当的监听器
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}

注册静态指定的监听器和beanFactory内的监听器Bean对象【不会导致监听器Bean对象实例化,仅记录其Bean名】到当前上下文 的多播器,然后发布在多播程序设置之前发布的ApplicationEvent集到各个监听器中

finishBeanFactoryInitialization(beanFactory);

/**
	 * Finish the initialization of this context's bean factory,
	 * initializing all remaining singleton beans.
	 * <p>完成这个上下文BeanFactory的初始化,初始化所有剩余的 单例Bean对象</p>
	 */
	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    
    
		// Initialize conversion service for this context.
		// 为此上下文初始化转换服务
		// 该beanFactory包含'conversionService'的BeanDefinition对象或外部注册的singleton实例 &&
		//		如果在beanFactory中 'conversionService' 与 ConversionService.class 匹配
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
    
    
			//从beanFactory中获取名为 'conversionService' 的 ConversionService 类型的Bean对象 作为 beanFactory的转换属性值
			// 	服务,也作为JavaBeans PropertyEditor的替代方案
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		// Register a default embedded value resolver if no bean post-processor
		// (such as a PropertyPlaceholderConfigurer bean) registered any before:
		// at this point, primarily for resolution in annotation attribute values.
		// 如果以前没有BeanPostProcessor(比如 PropertyPlaceholderConfigurer Bean)注册过任何Bean,
		// 那么注册一个默认的内嵌值解析器:此时,主要是为了解析注释属性值
		// 如果当前beanFactory没有字符串解析器,默认是有一个 PropertyPlaceHolderConfigurer 解析器的
		if (!beanFactory.hasEmbeddedValueResolver()) {
    
    
			//新建一个StringValueResolver对象添加字符串解析器
			beanFactory.addEmbeddedValueResolver(strVal ->
					//获取当前环境对象,在strVal中解析${...}占位符,用getProperty解析的相应属性值 替换它们。
					// 	带有无默认值的不可解析的占位符将被忽略通过原样传递。
					getEnvironment().resolvePlaceholders(strVal));
		}

		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		// 尽早初始化 LoadTimeWeaverAware Bean,以便尽早注册它们的转换器
		//获取与BeanPostProcessor.class(包括子类)匹配的bean名称,如果是FactoryBeans会根据beanDefinition 或getObjectType的值判断
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		//遍历weaverAwareNames
		for (String weaverAwareName : weaverAwareNames) {
    
    
			//获取在BeanFactory中weaverAwareName对应的Bean对象
			getBean(weaverAwareName);
		}

		// Stop using the temporary ClassLoader for type matching.
		// 停止使用临时类加载器进行类型匹配
		beanFactory.setTempClassLoader(null);

		// Allow for caching all bean definition metadata, not expecting further changes.
		// 允许缓存所有BeanDefinition元数据,而不期望进一步的更改
		//冻结所有beanDefinition,表示不再进一步修改或后处理已注册的BeanDefinition,这允许工厂积极地缓存bean定义元数据
		beanFactory.freezeConfiguration();

		// Instantiate all remaining (non-lazy-init) singletons.
		// 实例化所有剩余的(非延迟初始化)单例
		//确保所有非延迟初始化单例化都已实例化,同时也要考虑FactoryBean。
		beanFactory.preInstantiateSingletons();
	}

finishRefresh()

/**
	 * <p>完成刷新
	 * Finish the refresh of this context, invoking the LifecycleProcessor's
	 * onRefresh() method and publishing the
	 * {@link org.springframework.context.event.ContextRefreshedEvent}.
	 * <p>调用 LifecycleProcessor 的 onRefresh() 方法并发布 ContextRefreshedEvent ,完成上下
	 * 问刷新</p>
	 */
	protected void finishRefresh() {
    
    
		// Clear context-level resource caches (such as ASM metadata from scanning).
		// 清楚上下文级别的资源缓存(如扫描的ASM元数据)
		// 清空在资源加载器中的所有资源缓存
		clearResourceCaches();

		// Initialize lifecycle processor for this context.
		// 为这个上下文初始化生命周期处理器
		// 初始化 LifecycleProcessor.如果上下文中找到 'lifecycleProcessor' 的 LifecycleProcessor Bean对象,
		// 		则使用 DefaultLifecycleProcessor
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		// 首先将刷新传播到生命周期处理器
		// 上下文刷新的通知,例如自动启动的组件
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		// 发布最终事件
		// 新建 ContextRefreshedEvent 事件对象,将其发布到所有监听器。
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		// 参与 LiveBeansView MBean,如果是活动的
		// LiveBeansView:Sping 用于支持 JMX 服务的类,详情请参考:https://www.jianshu.com/p/fa4e88f95631
		// 注册 当前上下文 到 LiveBeansView,以支持 JMX 服务
		LiveBeansView.registerApplicationContext(this);
	}

完成刷新:

  1. 清空在资源加载器中的所有资源缓存
  2. 初始化 LifecycleProcessor.如果上下文中找到 ‘lifecycleProcessor’ 的 LifecycleProcessor Bean对象, 则使用 DefaultLifecycleProcessor
  3. 将刷新传播到生命周期处理器
  4. 新建 ContextRefreshedEvent 事件对象,将其发布到所有监听器。
  5. 注册 当前上下文 到 LiveBeansView,以支持 JMX 服务

Spring 5 ApplicationContext#refresh() --finishRefresh 源码解析

destroyBeans

/**
	 * Template method for destroying all beans that this context manages.
	 * The default implementation destroy all cached singletons in this context,
	 * invoking {@code DisposableBean.destroy()} and/or the specified
	 * "destroy-method".
	 * <p>用于销毁此上下文管理的所有bean的模板方法。
	 * 默认实现此上下文中销毁所有缓存的单例,调用{@code DisposableBean.destroy()}和
	 * 或指定的'destory-method'</p>
	 *
	 * <p>Can be overridden to add context-specific bean destruction steps
	 * right before or right after standard singleton destruction,
	 * while the context's BeanFactory is still active.
	 * <p>可以被覆盖以添加上下文特定的bean销毁步骤在标准单例销毁之前或之后,在上下文
	 * 的BeanFactory仍处于活动状态时</p>
	 *
	 * @see #getBeanFactory()
	 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons()
	 */
	protected void destroyBeans() {
    
    
		//销毁在工厂中的所有单例bean,包括已注册为一次性的内部bean。在工厂关闭时调用。
		getBeanFactory().destroySingletons();
	}

cancelRefresh(ex);

/**
	 * Cancel this context's refresh attempt, resetting the {@code active} flag
	 * after an exception got thrown.
	 * <p> 取消 此上下文的刷新尝试,在抛出异常后 重置 active 标志</p>
	 * @param ex the exception that led to the cancellation
	 *           -- 导致取消的异常
	 */
	protected void cancelRefresh(BeansException ex) {
    
    
		this.active.set(false);
	}

这里仅分析SpringBoot所用到的 GenericApplicationContext 实现

@Override
	protected void cancelRefresh(BeansException ex) {
    
    
		//将保存序列化ID设置为null
		this.beanFactory.setSerializationId(null);
		super.cancelRefresh(ex);
	}

resetCommonCaches();

/**
	 * Reset Spring's common reflection metadata caches, in particular the
	 * {@link ReflectionUtils}, {@link AnnotationUtils}, {@link ResolvableType}
	 * and {@link CachedIntrospectionResults} caches.
	 * <p>在 Spring 的核心中重置常见的自省缓存,因为我们可能不再需要单例bean的元数据了</p>
	 * @since 4.2
	 * @see ReflectionUtils#clearCache()
	 * @see AnnotationUtils#clearCache()
	 * @see ResolvableType#clearCache()
	 * @see CachedIntrospectionResults#clearClassLoader(ClassLoader)
	 */
	protected void resetCommonCaches() {
    
    
		//将ReflectionUtil的DeclaredMethod缓存,declaredFields缓存清空【使用ReflectionUtil来解析出类的DeclaredMethod,declaredFields都会加入到该缓存中】
		ReflectionUtils.clearCache();
		//清除内部注解元数据缓存
		AnnotationUtils.clearCache();
		//清除内部的ResolvableType缓存和SerializableTypeWrapper缓存
		ResolvableType.clearCache();
		//CachedIntrospectionResults:为Java类缓存JavaBeans PropertyDescriptor信息的内部类。不打算由应用程序代码直接 使用
		//清除当前的类加载器的自省缓存,删除该类加载器下所有类的自省结果,并从接受列表中删除类加载器(及其子类)
		CachedIntrospectionResults.clearClassLoader(getClassLoader());
	}

删除ReflectionUtils,AnnotationUtils,ResolvableType的缓存,清除当前的类加载器的自省缓存,删除该类加载器下 所有类的自省结果,并从接受列表中删除类加载器(及其子类)

猜你喜欢

转载自blog.csdn.net/qq_30321211/article/details/108325768