窥探-spring boot项目启动运行refreshContext()

窥探-spring boot项目启动运行refreshContext

  • applicationContext.refresh()
  • prepareRefresh方法
  • obtainFreshBeanFactory方法
  • loadBeanDefinitions方法加载注册bean
    • 准备context中使用的bean factory
      • prepareBeanFactory方法
    • postProcessBeanFactory方法
    • invokeBeanFactoryPostProcessors方法
      • PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors
      • PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
      • initMessageSource方法
      • initApplicationEventMulticaster方法
      • onRefresh方法需要相关子类去实现操作,这个在后面在看!
      • 注册ApplicationListener 方法registerListeners
      • 完成beanFactory的初始化,并初始化所有的单例bean
      • 发布所有的时间 finishRefresh()

之前我们查看了SpringApplication.run()方法里面相关的操作,里面有一个很重要的方法,也是核心的方法就是我们进行要讲的refreshContext,这个方法最后调用的是applicationContext.refresh(),我们都知道是整个spring环境的上下文,我们就来一探究竟!

applicationContext.refresh()

在进行运行环境的判断情况下,就要开始加载相关的bean,属性文件的处理,属性值的处理等等操作。
在这里插入图片描述
进入refresh方法,可以看到当前这个方式是接口ConfigurableApplicationContext接口中的一个方法,这个方法有
窥探-spring boot项目启动运行refreshContext()_第1张图片
当前这个类有28个实现类
窥探-spring boot项目启动运行refreshContext()_第2张图片
我们直接看AbstractApplicationContext这个类,ApplicationContext接口的抽象实现。 不要求用于配置的存储类型; 简单地实现通用上下文功能。 使用模板方法设计模式,需要具体的子类来实现抽象方法。我们来看看这个类中的refresh方法:

public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		//准备进行刷新context
		prepareRefresh();
		//告诉子类刷新内部bean factory
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		// 准备context中使用的bean factory
		prepareBeanFactory(beanFactory);
		try {
			//允许在context子类中对bean factory进行后处理
			postProcessBeanFactory(beanFactory);
			//调用在context中注册为bean的工厂处理器
			invokeBeanFactoryPostProcessors(beanFactory);
			//注册拦截Bean创建的Bean处理器
			registerBeanPostProcessors(beanFactory);
			//为context初始化消息源
			initMessageSource();
			//为context初始化事件多播器
			initApplicationEventMulticaster();
			//在特定context子类中初始化其他特殊bean
			onRefresh();
			//检查侦听器bean并注册它们
			registerListeners();
			//实例化所有剩余的(非延迟初始化)单例
			finishBeanFactoryInitialization(beanFactory);
			//最后一步:发布相应的事件
			finishRefresh();
		}catch (BeansException ex) {
			//销毁已创建的单例以避免资源悬空
			destroyBeans();
			//重置active标记.
			cancelRefresh(ex);
			//将异常传播给调用者
			throw ex;
		}finally {
			//在Spring的核心中重置常见的自省缓存,因为我们可能再也不需要单例bean的元数据了
			resetCommonCaches();
		}
	}
}

我们将一个方法一个方法的进行剖析refresh方法。

prepareRefresh方法

准备context以进行刷新,设置其启动日期和活动标志以及执行属性源的任何初始化。

protected void prepareRefresh() {
	// 切换启动状态.
	this.startupDate = System.currentTimeMillis();
	this.closed.set(false);
	this.active.set(true);  //启动状态设置为true
	//在context环境中初始化任何占位符属性源
	//这个方法在AbstractApplicationContext相关的子类中进行实现
	initPropertySources();
	//验证所有标记为必需的属性都是可解析的
	//ConfigurablePropertyResolver#setRequiredProperties
	getEnvironment().validateRequiredProperties();
	//存储预刷新的ApplicationListeners 
	if (this.earlyApplicationListeners == null) {
		this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
	}
	else {
		// 将本地应用程序侦听器重置为预刷新状态
		this.applicationListeners.clear();
		this.applicationListeners.addAll(this.earlyApplicationListeners);
	}
	//允许收集早期的ApplicationEvent,一旦多播器可用,便会发布
	this.earlyApplicationEvents = new LinkedHashSet<>();
}

验证相关的属性:
窥探-spring boot项目启动运行refreshContext()_第3张图片
通过PropertyResolver接口实现类加载先关的属性

obtainFreshBeanFactory方法

这个方法的作用是告诉子类刷新内部的bean factory
在这里插入图片描述
refreshBeanFactory调用:
此实现对此context的基础bean工厂执行实际的刷新,关闭前一个bean工厂(如果有),并为上下文生命周期的下一阶段初始化一个新的bean工厂。
窥探-spring boot项目启动运行refreshContext()_第4张图片
销毁此上下文管理的所有bean的模板方法。默认实现销毁此上下文中的所有缓存单例,调用DisposableBean.destroy()]和/或指定的“ destroy-method”。可以重写以添加context- 特定的bean销毁步骤在标准单例销毁之前或之后执行,而上下文的BeanFactory仍处于活动状态。
在这里插入图片描述
窥探-spring boot项目启动运行refreshContext()_第5张图片
删除之后在进行创建bean,为此创建一个内部bean工厂
在这里插入图片描述
如果有实现ConfigurableApplicationContext,返回父context的内部beanFactory,否则返回父context
在这里插入图片描述
自定义内部beanFactory使用当前的context
窥探-spring boot项目启动运行refreshContext()_第6张图片
通常通过以下方式将bean定义加载到给定的bean工厂中:
委托给一个或多个bean定义阅读器。

loadBeanDefinitions方法加载注册bean

/**为register(Class ...)指定的任何类注册BeanDefinition并扫描所有包对于由setConfigLocation(String)或
setConfigLocations(String [])指定的任何值,请首先尝试将每个位置作为类加载,如果类加载成功并且类加载成功,
则注册BeanDefinition 失败(引发ClassNotFoundException),
假定该值是一个包,并尝试对其进行扫描以查找组件类。启用默认的批注配置后处理器集,例如可以使用@ Autowired,@ Required和关联的批注。
配置类Bean定义会使用生成的Bean定义名称进行注册,除非为原型注释提供了value属性。
**/
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
	//通过AnnotatedBeanDefinitionReader注册BeanDefinition
	AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
	//进行扫描classpath注册BeanDefinition
	ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);
	BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
	if (beanNameGenerator != null) {
		reader.setBeanNameGenerator(beanNameGenerator);
		scanner.setBeanNameGenerator(beanNameGenerator);
		//注册单例bean
	beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
	}
	ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
	if (scopeMetadataResolver != null) {
	reader.setScopeMetadataResolver(scopeMetadataResolver);
	scanner.setScopeMetadataResolver(scopeMetadataResolver);
	}
	if (!this.componentClasses.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering component classes: [" +		StringUtils.collectionToCommaDelimitedString(this.componentClasses) + "]");
		}
	//进行注册,注册一个或多个要处理的组件类
	reader.register(ClassUtils.toClassArray(this.componentClasses));
	}
	if (!this.basePackages.isEmpty()) {
		//进行扫描注册
	scanner.scan(StringUtils.toStringArray(this.basePackages));
	}
	//获取相关的配置
	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		for (String configLocation : configLocations) {
			try {
				Class<?> clazz = ClassUtils.forName(configLocation, getClassLoader());
				if (logger.isTraceEnabled()) {
					logger.trace("Registering [" + configLocation + "]");
				}
				reader.register(clazz);
			}
			catch (ClassNotFoundException ex) {
				int count = scanner.scan(configLocation);
				if (count == 0 && logger.isDebugEnabled()) {
					logger.debug("No component classes found for specified class/package [" + configLocation + "]");
				}
			}
		}
	}
}

准备context中使用的bean factory

prepareBeanFactory方法

配置工厂的标准context特征,如上下文的ClassLoader和后处理器。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// 告诉内部bean工厂使用context的类加载器等
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
	//使用context回调配置Bean工厂
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory接口未在普通工厂中注册为可解析类型
	// essageSource注册为Bean(并发现用于自动装配)
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);
	// 注册早期的后处理器以将内部bean检测为ApplicationListeners
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// 如果发现LoadTimeWeave
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// 设置一个临时的ClassLoader以进行类型匹配
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// 注册默认环境bean
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
	beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
	beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
	beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}

postProcessBeanFactory方法

注册request/session作用域(AbstractRefreshableWebApplicationContext.class):
窥探-spring boot项目启动运行refreshContext()_第7张图片

注册ServletContextAwareProcessor(GenericWebApplicationContext.class):
窥探-spring boot项目启动运行refreshContext()_第8张图片

invokeBeanFactoryPostProcessors方法

/**
实例化并调用所有已注册的BeanFactoryPostProcessor Bean,
遵守明确的命令(如果有)
必须在单例实例化之前调用。
**/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
	// 检测LoadTimeWeaver并准备编织(如果在此期间发现)
	// 例如 通过ConfigurationClassPostProcessor注册的@Bean方法
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

	// 如果有的话,首先调用BeanDefinitionRegistryPostProcessors
	Set<String> processedBeans = new HashSet<>();
	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryProcessor =
					(BeanDefinitionRegistryPostProcessor) postProcessor;
				registryProcessor.postProcessBeanDefinitionRegistry(registry);
				registryProcessors.add(registryProcessor);
			}
			else {
				regularPostProcessors.add(postProcessor);
			}
		}

		// 不要在这里初始化FactoryBeans:我们需要保留所有常规bean
		// 未初始化,让Bean工厂后处理器对其应用
		// 在实现的BeanDefinitionRegistryPostProcessor之间分开
		// PriorityOrdered,Ordered和其他
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
		//首先,调用实现PriorityOrdered的BeanDefinitionRegistryPostProcessors
		String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		currentRegistryProcessors.clear();
		// 接下来,调用实现Ordered的BeanDefinitionRegistryPostProcessors
		postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		currentRegistryProcessors.clear();

		// 最后,调用所有其他BeanDefinitionRegistryPostProcessor,直到没有其他的出现
		boolean reiterate = true;
		while (reiterate) {
			reiterate = false;
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
					reiterate = true;
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();
		}

		// 现在,调用到目前为止已处理的所有处理器的postProcessBeanFactory回调
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// 调用在上下文实例中注册的工厂处理器
	    invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	// 不要在这里初始化FactoryBeans:我们需要保留所有常规bean
	// 未初始化,以让bean工厂后处理程序应用于它们
	String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

	// 在实现PriorityOrdered的BeanFactoryPostProcessor之间分开,
	// Ordered, and the rest.
	List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	List<String> orderedPostProcessorNames = new ArrayList<>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	for (String ppName : postProcessorNames) {
		if (processedBeans.contains(ppName)) {
			// 跳过-已在上面的第一阶段处理过
		}
		else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// 首先,调用实现PriorityOrdered的BeanFactoryPostProcessors。
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	// 接下来,调用实现Ordered的BeanFactoryPostProcessors。
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// 最后,调用所有其他beanfactorypostprocessor.
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

	// 清除缓存的合并bean定义,因为后处理器可能已经修改了原始元数据,例如 替换值中的占位符...
	beanFactory.clearMetadataCache();
}

PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);

实例化并注册所有BeanPostProcessor bean,遵守明确的命令(如果有)必须在应用程序bean的任何实例化之前调用。

public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

	// 注册BeanPostProcessorChecker,当在BeanPostProcessor实例化期间创建Bean时,即当某个Bean不适合所有BeanPostProcessor处理时,记录一条信息消息
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// 在实现PriorityOrdered的BeanPostProcessor之间分开
	// Ordered, and the rest.
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
	List<String> orderedPostProcessorNames = new ArrayList<>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	for (String ppName : postProcessorNames) {
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			priorityOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// 首先,注册实现PriorityOrdered的BeanPostProcessor
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	// 接下来,注册实现Ordered的BeanPostProcessor。
	List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
	for (String ppName : orderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		orderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);

	// 现在,注册所有常规BeanPostProcessor
	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
	for (String ppName : nonOrderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		nonOrderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

	// 最后,重新注册所有内部BeanPostProcessor
	sortPostProcessors(internalPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, internalPostProcessors);

	// 重新注册后处理器以将内部bean检测为ApplicationListener,将其移至处理器链的末尾(用于拾取代理等)
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
	// Nothing to sort?
	if (postProcessors.size() <= 1) {
		return;
	}
	Comparator<Object> comparatorToUse = null;
	if (beanFactory instanceof DefaultListableBeanFactory) {
		comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
	}
	if (comparatorToUse == null) {
		comparatorToUse = OrderComparator.INSTANCE;
	}
	postProcessors.sort(comparatorToUse);
}

以上两个方法将在后面讲解。

initMessageSource方法

//初始化MessageSource,如果在此context中未定义,则使用父级的
protected void initMessageSource() {
	//得到beanFactory
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	//判断本地是否含有“messageSource”的bean
	if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
		this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
		// 使MessageSource知道父MessageSource
		if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
			HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
			if (hms.getParentMessageSource() == null) {
				// 如果没有父MessageSource,则仅将父上下文设置为父MessageSource已经注册
				hms.setParentMessageSource(getInternalParentMessageSource());
			}
		}
	}
	else {
		// 使用空的MessageSource可以接受getMessage调用。
		DelegatingMessageSource dms = new DelegatingMessageSource();
		dms.setParentMessageSource(getInternalParentMessageSource());
		this.messageSource = dms;
		beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
	}
}

initApplicationEventMulticaster方法

//初始化ApplicationEventMulticaster,如果在context中没有定义,则使用SimpleApplicationEventMulticaster
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	//获得applicationEventMulticaster的bean
	if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
		this.applicationEventMulticaster =
		beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
	}
	else {
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
	}
}

onRefresh方法需要相关子类去实现操作,这个在后面在看!

注册ApplicationListener 方法registerListeners

首先注册静态指定的侦听器
在这里插入图片描述
不要在这里初始化FactoryBeans:我们需要保留所有未初始化的常规bean,以便后处理器对其应用!
在这里插入图片描述
多播器
窥探-spring boot项目启动运行refreshContext()_第9张图片

完成beanFactory的初始化,并初始化所有的单例bean

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// 为此context初始化转换服务
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
			beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}
	// 如果没有bean后处理器,则注册默认的嵌入式值解析器
	// (例如PropertyPlaceholderConfigurer bean)之前注册过的任何东西:这主要是为了解析注释属性值
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
	}
	// 尽早初始化LoadTimeWeaverAware Bean,以便尽早注册其转换器
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}
	// 停止使用临时ClassLoader进行类型匹配
	beanFactory.setTempClassLoader(null);
	// 允许缓存所有bean定义元数据,而不期望进一步的更改
	beanFactory.freezeConfiguration();
	// 实例化所有剩余的(非延迟初始化)单例
	beanFactory.preInstantiateSingletons();
}

发布所有的时间 finishRefresh()

//完成此上下文的刷新,调用LifecycleProcessor的onRefresh()方法并发布ContextRefreshedEvent
protected void finishRefresh() {
	// 清除上下文级别的资源缓存(如扫描的ASM元数据)
	clearResourceCaches();
	// 为此上下文初始化生命周期处理器
	initLifecycleProcessor();
	// 首先将刷新传播到生命周期处理器
	getLifecycleProcessor().onRefresh();
	// 发布最终事件
	publishEvent(new ContextRefreshedEvent(this));
	// Participate in LiveBeansView MBean, if active.
	LiveBeansView.registerApplicationContext(this);
}

到这里应该就是刷新基本上就结束了,我们进行梳理一下:
在启动spring的时候,会对当前的context进行相关操作,如果找不到当前的context就会去寻找parent context,进行相关的操作。
applicationContext.refresh的操作流程如下:

  • 准备进行刷新context:prepareRefresh()
  • 告诉子类刷新内部bean factory:ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  • 准备context中使用的bean factory
  • 允许在context子类中对bean factory进行后处理
  • 调用在context中注册为bean的工厂处理器
  • 注册拦截Bean创建的Bean处理器
  • 为context初始化消息源
  • 为context初始化事件多播器
  • 在特定context子类中初始化其他特殊bean
  • 检查侦听器bean并注册它们
  • 实例化所有剩余的(非延迟初始化)单例
  • 发布相应的事件

如果出现异常,将会销毁bean,同时重置active标记,最后会在Spring的核心中重置常见的自省缓存,因为我们可能再也不需要单例bean的元数据了。

你可能感兴趣的:(Spring,Boot)