本文基于web容器的spring源码解析,入口类为配置在web.xml中的监听器ContextLoaderListener

下图是refresh方法的逻辑:
在这里插入图片描述

入口方法

contextInitialized方法为初始化方法:

	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}

点进initWebApplicationContext方法,进入了ContextLoader类:

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
		...
		try {
			// 创建一个ApplicationContext,默认是WebApplicationContext
			if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
				if (!cwac.isActive()) {
					// 第一次初始化设置父容器
					if (cwac.getParent() == null) {
						cwac.setParent(parent);
					}
					
					//容器初始化
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}
			...
	}

configureAndRefreshWebApplicationContext方法中有段代码wac.refresh(),调用了容器的refresh方法,这里开始真正的进行容器的初始化逻辑。

refresh - 容器的初始化

refresh方法在类AbstractApplicationContext中有实现:

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// 刷新前的预处理
			prepareRefresh();

			// 创建真正的容器,加载BeanDefinition并注册到BeanDefinitionRegistry
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 工厂的预准备工作
			prepareBeanFactory(beanFactory);

			try {
				// BeanFactory的后置处理
				postProcessBeanFactory(beanFactory);

				// 执行实现了BeanFactoryPostProcessor的bean
				// 比如PropertyPlaceHoldConfigure就是在这里被调用,将xml中的${}配置替换掉
				// BeanFactoryPostProcessor是针对BeanDefinition的操作
				invokeBeanFactoryPostProcessors(beanFactory);

				//注册BeanPostProcessor(后置处理器)
				//比如用来实现@Autowired功能的AutowireAnnotationPostProcessor后置处理器
				//BeanPostProcessor针对bean实例操作
				registerBeanPostProcessors(beanFactory);

				// 初始化消息源
				initMessageSource();

				// 初始化事件派发器
				initApplicationEventMulticaster();

				// 子容器实现
				onRefresh();

				// 获取注册监听
				registerListeners();

				//  初始化非懒加载的单例bean实例(non-lazy-init)
				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();
			}
		}
	}

prepareRefresh-预处理

	protected void prepareRefresh() {
		this.startupDate = System.currentTimeMillis();
		this.closed.set(false);
		//标记为活跃状态,该状态在容器操作中用来判断一些执行条件
		this.active.set(true);

		if (logger.isInfoEnabled()) {
			logger.info("Refreshing " + this);
		}

		// 初始化属性设置
		initPropertySources();

		// 检验这些属性设置是否合法
		getEnvironment().validateRequiredProperties();
		
		// 用于保存容器中的一些早期的事情
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}

在初始化化容器中,主要做了三件事情,清除web容器中的缓存,获取初始化配置,检查这些配置的合法性。

如果是注解容器AnnotationConfigServletWebServerApplicationContext,那么预处理中还会做一些缓存的清理动作,比如spring boot启动的web容器。由于缓存清理代码很少,这里就不贴了。

其中初始化属性设置的方法initPropertySources()是个模板方法,方便其他具体子类实现。

校验属性设置时,判断该配置是否合法的依据仅仅是设置项不能为空,如果为空,将会直接抛出异常,异常信息如下:

The following properties were declared as required but could not be resolved: 【配置项名称】

obtainFreshBeanFactory - 获取BeanFactory

容器refresh预处理完成后,就会执行obtainFreshBeanFactory方法获取一个BeanFactory。

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		//刷新或者创建BeanFactory,其实是新建了一个
		refreshBeanFactory();
		//获取刚才创建的BeanFactory,就是一个简单的get方法
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();

		return beanFactory;
	}

方法refreshBeanFactory()是一个抽象方法,需要子类去实现它。以AbstractRefreshableApplicationContext为例,做了如下事情:

  1. 如果存在BeanFactory,销毁掉该工厂中的所有单列Bean信息,比如bean之间的依赖关系,类class信息
  2. 将之前创建的BeanFactory序列化id清除,引用指向为null
  3. 新建一个DefaultListableBeanFactory
  4. 执行loadBeanDefinitions方法进行BeanDefinition的定位、载入、和注册

prepareBeanFactory - BeanFactory的预准备工作

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// 设置类加载器,表达式解析器、属性编辑器
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// 添加一些在bean生命周期中可能要用到的东西,如ApplicationContextAwareProcessor,在bean初始化的时候判断该bean是否实现了各种类型的Aware接口
		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.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		// 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());
		}
	}

prepareBeanFactory方法在Beanfactory生效 做些准备工作:

  1. 设置BeanFactory的类加载器、表达式解析器、属性编辑器
  2. 添加部分BeanPostProcessor(ApplicationContextAwareProcessor),该处理器可以给实现了Aware接口的bean在创建的时候做些一些对应的装配,比如给实现了ApplicationContextAware接口的bean注入applicationContext上下文对象
  3. 设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、等,实现了这些接口的类不需要在创建的时候注入上下文
  4. 注册可以解析的自动装配;我们可以在任何组件中使用@Autowired注解的类型属性自动注入自动值,有四种类型的属性可以自动注入:
  • BeanFactory
  • ResourceLoader
  • ApplicationEventPublisher
  • ApplicationContext
  1. 添加BeanPostProcessor(ApplicationListenerDetector),该组件可以在bean初始化后做一些增强处理
  2. 添加编译时的AspectJ;
  3. 给BeanFactory中注册一些能用的组件;
    • environment【ConfigurableEnvironment】
    • systemProperties【Map<String, Object>】
    • systemEnvironment【Map<String, Object>】

postProcessBeanFactory - BeanFactory创建后的后置处理(额外需要初始化的东西)

这也是一个空方法,让子类来重写来,处理BeanFactory创建后的额外工作。比如:

  • 设置ServletContextAwareProcessor处理器
  • 像上步类似的还需要忽略需要自动装配的接口
  • 定制化容器的初始化设置

invokeBeanFactoryPostProcessors - 执行BeanFactory后置处理器

BeanFactoryPostProcessor是BeanFactory的后置处理器,在BeanFactory标准初始化之后执行的。
包括两个接口:

BeanDefinitionRegistryPostProcessor
BeanFactoryPostProcessor

beanFactory的后置处理逻辑在PostProcessorRegistrationDelegate类中invokeBeanFactoryPostProcessors方法:

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);
				}
			}

			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			//先处理实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor类型
			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);
			//执行处理器postProcessBeanDefinitionRegistry方法
			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();

			// 最后处理剩余的BeanDefinitionRegistryPostProcessors
			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();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);

以上代码很长,其实主要是对于俩种处理器分别按照实现的接口排序依次执行:

  1. 先执行BeanFactoryPostProcessor类型的处理器
  2. 先执行实现了PriorityOrdered接口的处理器,
  3. 然后执行实现了Ordered接口的处理器
  4. 最后执行剩下的处理器
  5. 对于实现了同一接口的处理器集合,会先排序然后再依次执行
  6. 等 BeanFactoryPostProcessor类型的处理器按以上排序规则全部执行完成后,再按着这个排序规则执行BeanFactoryPostProcessor类型的处理器

registerBeanPostProcessors - 注册bean后置处理器

与BeanFactory后置处理器类似,bean后置处理器的注册也是在类PostProcessorRegistrationDelegateregisterBeanPostProcessors方法中,beanPostProcessor注册指的是将这些处理器按照一定的顺序放入容器中,并且保证他们在容器中唯一:

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

		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.
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// 将处理器分成四类
		//实现了PriorityOrdered,MergedBeanDefinitionPostProcessor,Ordered接口的,以及剩余的
		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接口的
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// 注册实现了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);

		// 注册剩下的普通的
		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);

		// 注册实现了MergedBeanDefinitionPostProcessor接口的
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// 最后手动注册一个ApplicationListenerDetector
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

具体注册规则如下:
1、先注册实现了PriorityOrdered接口的处理器
2、注册实现了Ordered接口的处理器
3、注册其余没有优先级的普通处理器
4、再注册前面三种
理器之前,会把实现了MergedBeanDefinitionPostProcessor接口的处理器额外用个集合保存,等前三种全部注册完成后,再注册这种处理器
5、手动注册一个ApplicationListenerDetector,用来在bean创建完成后检查是否是ApplicationListeners

在这里我们有一个疑问,处理器可以同时实现排序接口和MergedBeanDefinitionPostProcessor的,或者只实现一个MergedBeanDefinitionPostProcessor接口,那么是如何保证,这个处理器最终优先级为4(MergedBeanDefinitionPostProcessor)呢。

看下容器注册处理器的方法:

	public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
		Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
		this.beanPostProcessors.remove(beanPostProcessor);
		this.beanPostProcessors.add(beanPostProcessor);
		if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
			this.hasInstantiationAwareBeanPostProcessors = true;
		}
		if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
			this.hasDestructionAwareBeanPostProcessors = true;
		}
	}

以上代码可以得知,在注册处理器的时候,如果发现容器中已经存在该处理器,会移除掉之前注册的,然后重新再注册一遍,这样就把之前靠前的排序移到后面了。

也就是说处理器如果实现了MergedBeanDefinitionPostProcessor接口,那么他在容器中的顺序排在其他类型的处理器之后处理器后面。

initMessageSource - 初始化MessageSource组件

initMessageSource主要是初始化一些消息组件,这些组件可以用于做国际化,消息绑定解析等。

protected void initMessageSource() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
			this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
			// 给HierarchicalMessageSource类型的消息设置父消息源
			if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
				HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
				if (hms.getParentMessageSource() == null) {
					hms.setParentMessageSource(getInternalParentMessageSource());
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Using MessageSource [" + this.messageSource + "]");
			}
		}
		else {
			// 默认创建一个空的消息源,使得容器可以提供getMessage方法的调用
			DelegatingMessageSource dms = new DelegatingMessageSource();
			dms.setParentMessageSource(getInternalParentMessageSource());
			this.messageSource = dms;
			beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
						"': using default [" + this.messageSource + "]");
			}
		}
	}

上面代码总结如下:

  1. 如果BeanFactory中注册了id为messageSource的bean,获取该实例
  2. 尝试给该消息源设置父消息源
  3. 如果BeanFactory中没有注册消息源,创建一个空的消息源,保证容器可以提供getMessage方法给其他地方调用
  4. 这个新建的空消息源也会注册到BeanFactory里面去

8、initApplicationEventMulticaster - 初始化事件派发器

	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 + "]");
			}
		}
	}

注册事件派发器的逻辑跟消息源类似:

  1. 如果BeanFactory中注册了id为applicationEventMulticaster的bean,获取该实例
  2. 如果不存在,创建SimpleApplicationEventMulticaster
  3. 将该实例注册到BeanFactory中

onRefresh - 传递给子类

onRefresh 是个空方法,给子类实现,让子类根据自己需要进行额外的初始化操作,比如初始化主题源。

registerListeners - 注册监听器

protected void registerListeners() {
		// 先放入已经准备好的
		for (ApplicationListener<?> listener : getApplicationListeners()) {
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

		// 从BeanFactory中获取实现了ApplicationListener接口的监听器并注册进来
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) {
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

		//把早期的事件也注册进来
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (earlyEventsToProcess != null) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}

从代码可知,主要把三种监听器放入事件派发器中:

  1. 已经放入容器的
  2. BeanFactory中实现了ApplicationListener接口的
  3. 早期事件,这些事件是在容器刷新前的预处理中定义的

finishBeanFactoryInitialization - 初始化剩余的单实例bean(非懒加载)

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// 初始化conversion转化器
		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后置处理器,注册一个默认的值解析器,这个解析器可以用来处理替换注解中的值
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

		//注册早期的LoadTimeWeaverAware
		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();

		// 注册剩余的非懒加载单实例bean
		beanFactory.preInstantiateSingletons();
	}

finishBeanFactoryInitialization方法负责将剩余的非懒加载(non-lazy-init)的单实例bean初始化,包括以下几种bean:

  • conversion转化器
  • 如果没有bean后置处理器,注册一个默认的值解析器,用于注解的值解析(PropertyPlaceholderConfigurer),比如那些占位符的值
  • 早期的LoadTimeWeaverAware,他可以用于aop中的通知织入
  • 剩余的非懒加载单实例bean

其中,我们看下注册剩余非懒加载单实例bean的beanFactory.preInstantiateSingletons()方法中的代码:

public void preInstantiateSingletons() throws BeansException {
		if (logger.isDebugEnabled()) {
			logger.debug("Pre-instantiating singletons in " + this);
		}

		// 先把所有的bean定义名称放入副本列表中中
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// 找到并注册所有非懒加载的单实例bean
		for (String beanName : beanNames) {
			//获取到这个beanName的定义信息
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			//非抽象,单列,非懒加载
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					//工厂bean只初始化需要立马创建的
					if (bean instanceof FactoryBean) {
						final FactoryBean<?> factory = (FactoryBean<?>) bean;
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
											((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

		// 设置bean初始化时的回调
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

bean真正初始化是在AbstractBeanFactory类的doGetBean方法中:

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

		final String beanName = transformedBeanName(name);
		Object bean;

		// 尝试从缓存中获取,如果能获取到,说明之前创建过
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// 未从缓存中获取到bean,开始bean的创建流程


			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// 父容器中有该BeanDefinition的话,让父容器创建该bean
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				String nameToLookup = originalBeanName(name);
				if (parentBeanFactory instanceof AbstractBeanFactory) {
					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
							nameToLookup, requiredType, args, typeCheckOnly);
				}
				else if (args != null) {
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}

			//标记该bean已创建
			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}

			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// 获取bean依赖的其他bean,如果有依赖bean的话,先把这些依赖的bean创建出来
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
					for (String dep : dependsOn) {
						if (isDependent(beanName, dep)) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
						}
						registerDependentBean(dep, beanName);
						try {
							getBean(dep);
						}
						catch (NoSuchBeanDefinitionException ex) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
						}
					}
				}

				// 单实例bean的创建
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				else {
					String scopeName = mbd.getScope();
					final Scope scope = this.scopes.get(scopeName);
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
					}
					try {
						Object scopedInstance = scope.get(beanName, () -> {
							beforePrototypeCreation(beanName);
							try {
								return createBean(beanName, mbd, args);
							}
							finally {
								afterPrototypeCreation(beanName);
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; consider " +
								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && !requiredType.isInstance(bean)) {
			try {
				T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
				if (convertedBean == null) {
					throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
				}
				return convertedBean;
			}
			catch (TypeMismatchException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Failed to convert bean '" + name + "' to required type '" +
							ClassUtils.getQualifiedName(requiredType) + "'", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

doGetBean方法中的代码有点长,我们对他的功能做个简单的总结:

  1. 创建前先尝试从单列bean集合中获取该bean,如果bean曾经被创建的话,会缓存到这个容器中,此时无需重复创建
  2. bean没被缓存过的话开始执行创建流程
  3. 如果这个bean是在父容器中创建的,那么让父容器执行doGetBean方法
  4. 给需要创建的bean做个标记,表示在创建了,防止其他线程创建该bean
  5. 查找该bean依赖的其他bean,如果有依赖的,先创建这些依赖的bean
  6. 执行createBean方法创建bean【下面会继续讲怎么】
  7. 检查创建的bean是否类型匹配

AbstractAutowireCapableBeanFactorycreateBean方法在创建bean前会尝试返回一个该bean的代理对象,如果有代理对象会直接返回,没有的话会执行doCreateBean方法,开始bean初始化逻辑:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

		// 实例化bean
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// 允许后置处理器对bean进行增强处理
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			// 赋值填充bean中的属性
			populateBean(beanName, mbd, instanceWrapper);
			//bean初始化方法
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

逻辑如下:

  1. 通过工厂方法或者构造器方法创建bean实例(这断代码很长,我们就不继续跟了,有兴趣可以自行点进去)
  2. 调用applyMergedBeanDefinitionPostProcessors方法,执行MergedBeanDefinitionPostProcessor类型的后置处理器的postProcessMergedBeanDefinition方法
  3. 调用populateBean方法,给bean的属性赋值
    • 执行InstantiationAwareBeanPostProcessor类型的后置处理器的postProcessAfterInstantiation方法
    • 执行InstantiationAwareBeanPostProcessor类型的后置处理器的postProcessPropertyValues方法
    • 执行applyPropertyValues方法设置值给bean
  4. 调用initializeBean方法初始化bean
    • invokeAwareMethods - 执行Aware接口的方法(BeanNameAware,BeanClassLoaderAware,BeanFactoryAware)
    • applyBeanPostProcessorsBeforeInitialization - 执行BeanPostProcessor类型后置处理器的postProcessBeforeInitialization方法
    • invokeInitMethods - 执行初始化方法
      • 如果bean实现了InitializingBean接口,执行afterPropertiesSet方法
      • 自定义方法,比如xml中设置default-init-method的值,或者@bean注解的initMethod
    • applyBeanPostProcessorsAfterInitialization - 执行BeanPostProcessor类型后置处理器的postProcessAfterInitialization方法
  5. 调用registerDisposableBeanIfNecessary方法注册bean销毁方法,也就是bean实现DisposableBean接口的destroy方法

bean创建出来后,会在DefaultSingletonBeanRegistry类中执行addSingleton方法,将新建出单例bean放入缓存中。

finishRefresh - 创建完成后的处理

	protected void finishRefresh() {
		// 清除容器级别的Resource缓存
		clearResourceCaches();

		// 初始化生命周期有关的后置处理器
		initLifecycleProcessor();

		// 将容器refresh这件事情传播给生命周期相关的处理器
		/ 也就是执行这些处理器的onRefresh回调方法
		getLifecycleProcessor().onRefresh();

		// 发布容器刷新完成事件
		publishEvent(new ContextRefreshedEvent(this));

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

五件事情:

  1. 清除容器级别的Resource缓存
  2. 初始化生命周期有关的后置处理器
  3. 执行签名初始化的生命周期相关的后至处理器的onRefresh方法
  4. 发布容器刷新完成事件
  5. 把容器注册到LiveBeansView中
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐