-- 以下内容均基于2.1.8.RELEASE版本

紧接着上一篇(四)SpringBoot启动过程的分析-预处理ApplicationContext, 本文将分析上下文容器准备完成之后开始执行刷新流程

// SpringApplication.java

private void refreshContext(ConfigurableApplicationContext context) {
	refresh(context);
	if (this.registerShutdownHook) {
		try {
			context.registerShutdownHook();
		}
		catch (AccessControlException ex) {
			// Not allowed in some environments.
		}
	}
}

// 真正的refresh方法在AbstractApplicationContext类中
protected void refresh(ApplicationContext applicationContext) {
	Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
	((AbstractApplicationContext) applicationContext).refresh();
}

// AbstractApplicationContext.java
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			initMessageSource();

			// Initialize event multicaster for this context.
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			onRefresh();

			// Check for listener beans and register them.
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			finishRefresh();
		}

		catch (BeansException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Exception encountered during context initialization - " +
						"cancelling refresh attempt: " + ex);
			}

			// Destroy already created singletons to avoid dangling resources.
			destroyBeans();

			// Reset 'active' flag.
			cancelRefresh(ex);

			// Propagate exception to caller.
			throw ex;
		}

		finally {
			// Reset common introspection caches in Spring's core, since we
			// might not ever need metadata for singleton beans anymore...
			resetCommonCaches();
		}
	}
}

在refresh方法中清晰的划分了刷新容器的步骤。

prepareRefresh()

主要用于清除元数据Reader的缓存,设置应用程序启动的时间,设置应用程序的活动标记,初始化属性源。

// AnnotationConfigServletWebServerApplicationContext.java

protected void prepareRefresh() {
	this.scanner.clearCache();
	super.prepareRefresh();
}

// AbstractApplicationContext.java

protected void prepareRefresh() {
	// 设置开始执行的时间和活动标记
	this.startupDate = System.currentTimeMillis();
	this.closed.set(false);
	this.active.set(true);

	if (logger.isDebugEnabled()) {
		if (logger.isTraceEnabled()) {
			logger.trace("Refreshing " + this);
		}
		else {
			logger.debug("Refreshing " + getDisplayName());
		}
	}

	// ①
	initPropertySources();

	// ②
	// Validate that all properties marked as required are resolvable:
	// see ConfigurablePropertyResolver#setRequiredProperties
	getEnvironment().validateRequiredProperties();

	// ③
	// Store pre-refresh ApplicationListeners...
	if (this.earlyApplicationListeners == null) {
		this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
	}
	else {
		// Reset local application listeners to pre-refresh state.
		this.applicationListeners.clear();
		this.applicationListeners.addAll(this.earlyApplicationListeners);
	}

	// Allow for the collection of early ApplicationEvents,
	// to be published once the multicaster is available...
	this.earlyApplicationEvents = new LinkedHashSet<>();
}

① - 初始化属性资源

// StandardServletEnvironment.java

public void initPropertySources(@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {
	WebApplicationContextUtils.initServletPropertySources(getPropertySources(), servletContext, servletConfig);
}

// WebApplicationContextUtils.java

public static void initServletPropertySources(MutablePropertySources sources,
		@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {

	Assert.notNull(sources, "'propertySources' must not be null");
	String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME;
	// servletContext不为空且有相关配置的情况
	if (servletContext != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) {
		sources.replace(name, new ServletContextPropertySource(name, servletContext));
	}
	// servletConfig不为空且有相关配置的情况
	name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME;
	if (servletConfig != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) {
		sources.replace(name, new ServletConfigPropertySource(name, servletConfig));
	}
}

在内部调用了WebApplicationContextUtils.initServletPropertySources方法,由名称可得知,它用于初始化Servlet的属性资源,在实际执行过程中分别根据ServletContext和ServletConfig的值来判定是否要将指定的配置包装为ServletContextPropertySource。在实际调试过程中他们的值都为空,也就是没有进行任何操作。

② - 检查必备属性,此处是用于检查哪些属性是必不可少的,例如可以设置"example.address"这个属性必须不为空。
③ - 重新对监听器排序

prepareBeanFactory(beanFactory)

// AbstractApplicationContext.java

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {

	// 设置类加载器
	// Tell the internal bean factory to use the context's class loader etc.
	beanFactory.setBeanClassLoader(getClassLoader());
	// 设置SpringEL表达式解析器
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	// 设置属性编辑器注册
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// ① 忽略指定的接口注入
	// Configure the bean factory with context callbacks.
	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,则实际将会指定它注入的是当前设置的BeanFactory
	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// 添加和移除ApplicationListener
	// Register early post-processor for detecting inner beans as ApplicationListeners.
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	//
	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// 注册默认环境对象
	// Register default environment beans.
	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());
	}
}

① - 这里的忽略依赖接口,是指这些Aware接口的实现类在Spring中将会自动忽略接口实现类中和setter方法入参相同的类型,举例说明

public interface EnvironmentAware extends Aware {
	void setEnvironment(Environment environment);
}

public class MyEnvironmentAware implements Environment {

	private Environment environment;

	@Overwired
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}

}

示例中展示了如何使用EnvironmentAware接口来实现在自定义代码中获取Environment,上面所说的忽略,是指在Spring自动装配MyEnvironment这个类的时候,会自动忽略到setEnvironment方法中的Environment对象注入。
在忽略接口的第一行代码添加了一个ApplicationContextAwareProcessor,而它则是Spring框架统一来设置这些Aware接口实现类的处理器。

postProcessBeanFactory(beanFactory)

在当前AbstractApplicationContext类中的postProcessBeanFactory方法并未实现,由其子类实现。

// AnnotationConfigServletWebServerApplicationContext.java
// 实现一
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// ①
	super.postProcessBeanFactory(beanFactory);
	// ②
	if (this.basePackages != null && this.basePackages.length > 0) {
		this.scanner.scan(this.basePackages);
	}
	// ③
	if (!this.annotatedClasses.isEmpty()) {
		this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
	}
}

① - 调用父类的实现

// ServletWebServerApplicationContext.java

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// 添加用于处理WebApplicationContextServletContextAware接口的processor
	beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
	// 忽略ServletContextAware接口的注入
	beanFactory.ignoreDependencyInterface(ServletContextAware.class);
	registerWebApplicationScopes();
}

// 注册web应用的作用域
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,
		@Nullable ServletContext sc) {

	beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
	beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
	if (sc != null) {
		ServletContextScope appScope = new ServletContextScope(sc);
		beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
		// Register as ServletContext attribute, for ContextCleanupListener to detect it.
		sc.setAttribute(ServletContextScope.class.getName(), appScope);
	}

	beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
	beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
	beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
	beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
	if (jsfPresent) {
		FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
	}
}

② - 根据basePackage指定的位置进行扫描bean
③ - 根据注解来扫描指定的bean

invokeBeanFactoryPostProcessors()

主要用于调用BeanFactoryPostProcessors的实现

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	// 调用BeanFactoryPostProcessor
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

	// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
	// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}

在调用BeanFactoryPostProcessor时,会首先调用BeanDefinitionRegistryPostProcessor, 因为后者是对前者的扩展,并且有可能在后者中又重新注册了前者的其他实例。由于PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()方法过长,这里直接写行内注释能够比较
直观的分析前后关系。

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

	// Invoke BeanDefinitionRegistryPostProcessors first, if any.
	// 已处理的Bean
	Set<String> processedBeans = new HashSet<>();

	// 判断当前的BeanFactory是否为一个Bean注册器,实际上就是代表同时实现了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor接口的实现
	// 对于同时实现两个接口的类,将先调用BeanDefinitionRegistryPostProcessor里面的方法,再调用BeanFactoryPostProcessor里面的方法
	// 在调用的时候又要区分是实现了PriorityOrdered还是Ordered接口。
	if (beanFactory instanceof BeanDefinitionRegistry) {

		// 转换为注册器
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		// 用于存放常规的BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
		// 用于存放BeanFactoryPostProcessor的扩展BeanDefinitionRegistryPostProcessor,这里是一个汇总的列表
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

		// 遍历传入的BeanFactoryPostProcessor
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			// 优先执行BeanFactoryPostProcessor的扩展类BeanDefinitionRegistryPostProcessor,它的优先级最高
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				// 类型转换
				BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
				// 调用postProcessBeanDefinitionRegistry()方法,内部可能注册了Bean,也可能重新定义了一些普通的BeanFactoryPostProcessor
				registryProcessor.postProcessBeanDefinitionRegistry(registry);
				// 添加到已处理列表
				registryProcessors.add(registryProcessor);
			}
			else {
				//	对比上面if代码块会发现,这里没有作调用,直接先保存在常规列表内部,因为常规的Processor在调用的时候还有其他考虑,接着往下看便是
				regularPostProcessors.add(postProcessor);
			}
		}

		// 不要在这里初始化FactoryBean(请看清是FactoryBean,工厂类,不是类工厂(BeanFactory),他们有巨大的差异),需要保留所有的常规类未初始化,以便使用BeanFactoryPostProcessor对其处理
		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!

		// 根据BeanDefinitionRegistryPostProcessors 实现的接口划分为三类:实现了PriorityOrdered的、实现了Ordered的以及前面两者都没实现的
		// Separate between BeanDefinitionRegistryPostProcessors that implement
		// PriorityOrdered, Ordered, and the rest.

		// 保存当前将要处理的BeanDefinitionRegistryPostProcessor列表,每处理完一种分类的就清空
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

		// 首先调用实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessors
		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.

		// 获取当前Bean工厂内部所有的,类型为BeanDefinitionRegistryPostProcessor.class的后处理器名称
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// 筛选出实现了PriorityOrdered接口的后处理器,放入当前处理列表
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				// 同时放入已处理列表
				processedBeans.add(ppName);
			}
		}

		// 按照优先级排序
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		// 添加实现了PriorityOrder接口的BeanDefinitionRegistryPostProcessor到它的汇总列表里面
		registryProcessors.addAll(currentRegistryProcessors);
		// 调用所有的BeanDefinitionRegistryPostProcessor实例的postProcessBeanDefinitionRegistry()方法
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		// 清除内部的实现了PriorityOrder的BeanDefinitionRegistryPostProcessor
		currentRegistryProcessors.clear();

		// 上面是处理实现了PriorityOrdered接口的,这里处理实现了Ordered接口的, 为何这里又获取了一次postProcessorNames,前面不是才获取么?
		// 这里获取一次是因为前面处理的时候有可能又加入了新的BeanDefinitionRegistryPostProcessor
		// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
		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();

		// 继续调用普通的BeanDefinitionRegistryPostProcessors
		// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
		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();
		}

		// 最后调用普通的 BeanFactoryPostProcessor,
		// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

		//因为BeanDefinitionRegistryPostProcessor也是继承了BeanFactoryPostProcessor,,也具有postProcessBeanFactory()方法的,所以也需要执行
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// 若不是BeanDefinitionRegistry,那就是直接实现了BeanFactoryPostProcessor
		// Invoke factory processors registered with the context instance.
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	// 下面这部分逻辑就和上面套路一样,无非处理的是BeanFactoryPostProcessor罢了
	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let the bean factory post-processors apply to them!
	String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

	// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
	// 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)) {
			// skip - already processed in first phase above
		}
		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);
		}
	}

	// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// Finally, invoke all other BeanFactoryPostProcessors.
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

	// Clear cached merged bean definitions since the post-processors might have
	// modified the original metadata, e.g. replacing placeholders in values...
	beanFactory.clearMetadataCache();
}

小结

BeanFactoryPostProcessors是Spring框架中的一个很重要的扩展入口,通过它可以在Bean实例化之前进行一些修改,从类型上分为BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,在内部处理过程中,前者的优先级高于后者。与此同时,他们分别还会按照PriorityOrdered > Ordered > 默认
的优先级顺序来进行处理。了解他们执行顺序这点很重要,后续如有扩展需求就可以精准植入自己的逻辑。需要注意的是,这些处理器本身就是用于注册Bean,因此他们也可以注册和自己类型一样的扩展类。在使用的时候尤其要注意这点。例如在实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor中
再注册一个实现了Ordered的BeanDefinitionRegistryPostProcessor,虽然这样没问题,但笔者认为这样代码隐藏过深。不利于后期维护。建议使用SPI机制来配置,简洁明了。

registerBeanPostProcessors()

主要用于调用BeanPostProcessors的实现,区别于上一个章节,本章节处理的是实例化过后的Bean。

// AbstractApplicationContext.java

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	// 调用BeanPostProcessor
	PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}


// PostProcessorRegistrationDelegate.java

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

	// 获取所有的BeanPostProcessor名称
	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

	// Register BeanPostProcessorChecker that logs an info message when
	// a bean is created during BeanPostProcessor instantiation, i.e. when
	// a bean is not eligible for getting processed by all BeanPostProcessors.

	// 注册一个BeanPostProcessorChecker,当一个BeanPostProcessor在实例化期间创建一个Bean的时候,打印日志
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// 按照优先级整理

	// 实现了PriorityOrdered接口的BeanPostProcessor集合
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	// 内部定义的BeanPostProcessor集合
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
	// 实现了Ordered接口的BeanPostProcessor名称集合
	List<String> orderedPostProcessorNames = new ArrayList<>();
	// 未实现排序优先级接口的BeanPostProcessor名称集合
	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
	// First, register the BeanPostProcessors that implement PriorityOrdered.
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	// 注册实现了PriorityOrdered接口的BeanPostProcessor
	// Next, register the BeanPostProcessors that implement Ordered.
	List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
	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
	// Now, register all regular BeanPostProcessors.
	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	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
	// Finally, re-register all internal BeanPostProcessors.
	sortPostProcessors(internalPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, internalPostProcessors);

	// 注册ApplicationListenerDetector,它将在bean初始化完成之后检测是否为ApplicationListener,如果是则加入applicationListeners中
	// 在Bean销毁之前,提前从ApplicationEventMulticaster中删除
	// Re-register post-processor for detecting inner beans as ApplicationListeners,
	// moving it to the end of the processor chain (for picking up proxies etc).
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

initMessageSource()

初始化MessageSource,若当前上下文中未定义,则使用父类中的定义

// AbstractApplicationContext.java

protected void initMessageSource() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
		this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
		// Make MessageSource aware of parent MessageSource.
		if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
			HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
			if (hms.getParentMessageSource() == null) {
				// Only set parent context as parent MessageSource if no parent MessageSource
				// registered already.
				hms.setParentMessageSource(getInternalParentMessageSource());
			}
		}
		if (logger.isTraceEnabled()) {
			logger.trace("Using MessageSource [" + this.messageSource + "]");
		}
	}
	else {
		// Use empty MessageSource to be able to accept getMessage calls.
		DelegatingMessageSource dms = new DelegatingMessageSource();
		dms.setParentMessageSource(getInternalParentMessageSource());
		this.messageSource = dms;
		beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
		}
	}
}

initApplicationEventMulticaster()

主要用于设置事件发布器,若当前上下文没有定义ApplicationEventMulticaster 则使用 SimpleApplicationEventMulticaster

// AbstractApplicationContext.java

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.isTraceEnabled()) {
			logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
		}
	}
	else {
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
					"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
		}
	}
}

onRefresh()

当前类中没有实现,只是作为一个模板,将由子类来实现

// AbstractApplicationContext.java

protected void onRefresh() throws BeansException {
	// For subclasses: do nothing by default.
}

// ServletWebServerApplicationContext.java
protected void onRefresh() {
	// 父类中仅仅设置了一下主题,无关紧要
	super.onRefresh();
	try {
		// 创建Web服务器
		createWebServer();
	}
	catch (Throwable ex) {
		throw new ApplicationContextException("Unable to start web server", ex);
	}
}

创建Web服务器

这里只简单介绍一下它启动了内置的Web容器,Web容器的初始化后续会有单独篇章分析。

private void createWebServer() {
	// ①
	WebServer webServer = this.webServer;
	// ②
	ServletContext servletContext = getServletContext();
	// ③
	if (webServer == null && servletContext == null) {
		ServletWebServerFactory factory = getWebServerFactory();
		this.webServer = factory.getWebServer(getSelfInitializer());
	}
	// ④
	else if (servletContext != null) {
		try {
			getSelfInitializer().onStartup(servletContext);
		}
		catch (ServletException ex) {
			throw new ApplicationContextException("Cannot initialize servlet context", ex);
		}
	}
	// ⑤
	initPropertySources();
}

① - 当前应用的WEB服务器,也就是Servlet容器。
② - 当前应用的上下文,一个应用使用一个ServletContext来表示。
③ - 使用ServletWebServerFactory创建一个Servlet容器
④ - 手动配置上下文的接口。
⑤ - 初始化配置信息,实际上就是将环境信息中的'servletContextInitParams':StubPropertySource 转换为'servletContextInitParams': ServletContextPropertySource; 将 'servletConfigInitParams': StubPropertySource转换为'servletConfigInitParams':ServletConfigPropertySource

registerListeners()

主要用于将获取到的所有监听器委托给applicationEventMulticaster。

protected void registerListeners() {

	// ①
	// Register statically specified listeners first.
	for (ApplicationListener<?> listener : getApplicationListeners()) {
		getApplicationEventMulticaster().addApplicationListener(listener);
	}

	// ②
	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let post-processors apply to them!
	String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
	for (String listenerBeanName : listenerBeanNames) {
		getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
	}

	// ③
	// Publish early application events now that we finally have a multicaster...
	Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
	this.earlyApplicationEvents = null;
	if (earlyEventsToProcess != null) {
		for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
			getApplicationEventMulticaster().multicastEvent(earlyEvent);
		}
	}
}

① - 将内部注册的监听器委托给广播器applicationEventMulticaster。
② - 检测BeanFactory内部的监听器
③ - 发布早期事件

finishBeanFactoryInitialization()

实例化剩下的所有单例Bean(非延迟加载的)

// AbstractApplicationContext.java

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {

	// ①
	// Initialize conversion service for this 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));
	}

	// ②
	// 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.
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
	}

	// ③
	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// ④
	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// ⑤
	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

	// ⑤
	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}

① - 判断是否有转换服务
② - 判断是否有占位符解析器
③ - 注册LoadTimeWeaverAware
④ - 停止使用临时的ClassLoader进行类型匹配,实际上它就是空值
⑤ - 冻结所有的BeanDefinition,通过configurationFrozen = true 和 frozenBeanDefinitionNames(包含所有的BeanDefinition)配合锁定
⑥ - 实例化剩下的所有单例Bean(非延迟加载的),其实就是从注册器缓存里面取出(DefaultSingletonBeanRegistry)

finishRefresh()

// ServletWebServerApplicationContext.java
@Override
protected void finishRefresh() {
	// 父类执行finishRefresh
	super.finishRefresh();
	// 启动web容器
	WebServer webServer = startWebServer();
	if (webServer != null) {
		// 发布web容器启动完成事件
		publishEvent(new ServletWebServerInitializedEvent(webServer, this));
	}
}

// AbstractApplicationContext.java

protected void finishRefresh() {

	// ① Clear context-level resource caches (such as ASM metadata from scanning).
	clearResourceCaches();

	// ② Initialize lifecycle processor for this context.
	initLifecycleProcessor();

	// ③ Propagate refresh to lifecycle processor first.
	getLifecycleProcessor().onRefresh();

	// ④ Publish the final event.
	publishEvent(new ContextRefreshedEvent(this));

	// ⑤ Participate in LiveBeansView MBean, if active.
	LiveBeansView.registerApplicationContext(this);
}

① - 清除资源缓存
② - 初始化上下文生命周期
③ - 传播刷新动作至生命周期
④ - 发布上下文刷新完毕事件
⑤ - 构建当前Bean及其依赖关系的快照,设计用于Spring Tool Suite

resetCommonCaches()

主要用于清除Spring内部的缓存

// AbstractApplicationContext.java

protected void resetCommonCaches() {
	ReflectionUtils.clearCache();
	AnnotationUtils.clearCache();
	ResolvableType.clearCache();
	CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
03-31 04:59