Spring Bean生命周期源码解析

介绍

目前大部分的 Java 互联网项目,都是用 Spring作为基础框架,管理bean,融合其他框架。Spring Bean生命周期和我们日常开发密不可分,我们虽然可能不太了解原理,但每天都会用,且作为面试的重点、重灾区,让我们一探究竟。
我们众知的Spring Bean生命周期包含实例化、填充属性、初始化,这也是狭义上的Bean生命周期。
由于Spring Bean生命周期源内容较多,本文以较粗的粒度剖析源码,从spring启动到bean创建完成的过程,其他细节内容后期专门讲解。

源码解析

容器启动与包扫描

spring容器启动,注意本文的spring容器为AnnotationConfigApplicationContext,是基于注解的形式,你也可以使用基于xml形式的ClassPathXmlApplicationContext容器,原理相同。

	public AnnotationConfigApplicationContext(String... basePackages) {
		//初始化AnnotatedBeanDefinitionReader-读取注解的Bean读取器
		//初始化ClassPathBeanDefinitionScanner-包扫描器
		this();
		//包扫描操作
		scan(basePackages);
		//刷新spring容器,具体bean创建在其中
		refresh();
	}

scan最终会调用ClassPathBeanDefinitionScanner.doScan执行扫描操作,返回路径下BeanDefinitionHolder的集合。

	protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
		//BeanDefinitionHolder为封装BeanDefinition的对象
		Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
		//循环包扫描的路径
		for (String basePackage : basePackages) {
			//获取候选组件
			//过程:1.根绝路径匹配classPath下所有资源,即class文件
			//     2.循环资源,判断是否匹配,需匹配includeFilters
			Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
			for (BeanDefinition candidate : candidates) {
				//获取作用域元数据并设置至BeanDefinition
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				candidate.setScope(scopeMetadata.getScopeName());
				//获取beanName
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
				//若属于AbstractBeanDefinition,设置默认属性
				//lazyInit autowireMode dependencyCheck等
				if (candidate instanceof AbstractBeanDefinition) {
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
				//若属于AnnotatedBeanDefinition,设置对应属性
				//包含lazyInit primary dependsOn role description
				if (candidate instanceof AnnotatedBeanDefinition) {
					AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
				}
				//检查beanName有无冲突,不冲突则放入
				if (checkCandidate(beanName, candidate)) {
					BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
					definitionHolder =
							AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
					beanDefinitions.add(definitionHolder);
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}

refresh容器刷新

spring容器的初始化和bean创建的过程都在refresh中,我们也可通过beanFactory手动调用refresh方法,达到热加载bean的功能。

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			//准备工作:设置启动时间、是否激活标识位
			//初始化属性源(property source)配置
			prepareRefresh();
			//获取BeanFactory;
			//默认实现是DefaultListableBeanFactory,在创建容器的时候创建的
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
			//BeanFactory的预准备工作
			//如context的类加载器、BeanPostProcessor、Aware忽略等
			prepareBeanFactory(beanFactory);
			try {
				//BeanFactory准备工作完成后进行的后置处理工作
				//具体实现在不同的子类,如GenericWebApplicationContext添加
				//ServletContextAwareProcessor的BeanPostProcessor
				postProcessBeanFactory(beanFactory);
				//执行BeanFactoryPostProcessor的方法
				//主要执行spring自己的和我们自定义的BeanFactoryPostProcessor
				//此方法也是重点,后期专门文章介绍BeanFactoryPostProcessor
				invokeBeanFactoryPostProcessors(beanFactory);
				//注册BeanPostProcessor(Bean的后置处理器),
				//在创建bean的前后等执行
				registerBeanPostProcessors(beanFactory);
				//初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
				initMessageSource();
				//初始化事件派发器
				initApplicationEventMulticaster();
				 //子类重写这个方法,在容器刷新的时候可以自定义逻辑;
				 //如创建Tomcat,Jetty等WEB服务器
				onRefresh();
				 //注册应用的监听器。就是注册实现了ApplicationListener接口的监听器bean,这些监听器是注册到ApplicationEventMulticaster中的
				registerListeners();
				 //初始化所有剩下的非懒加载的单例bean
				finishBeanFactoryInitialization(beanFactory);
				//完成context的刷新。
				//主要是调用LifecycleProcessor的onRefresh()方法
				//并且发布事件(ContextRefreshedEvent)
				finishRefresh();
			}
			catch (BeansException ex) {
				destroyBeans();
				cancelRefresh(ex);
				throw ex;
			}
			finally {
				resetCommonCaches();
			}
		}
	}

finishBeanFactoryInitialization初始化剩下的非懒加载的单例bean

此方法为本文重点,我们定义的非懒加载单例bean都会在此方法中被加载,从beanDefinition转换成spring的bean。
finishBeanFactoryInitialization方法中调用beanFactory.preInstantiateSingletons()创建bean

@Override
	public void preInstantiateSingletons() throws BeansException {
		//将beanFactory中beanDefinitionNames取出构成beanNames 
		//beanDefinitionNames是扫描解析阶段放入
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
		//循环处理beanName 
		for (String beanName : beanNames) {
			//合并BeanDefinition,BeanDefinition存在父子关系,需将父类合并到子类
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			//RootBeanDefinition非抽象且单例且非懒加载,才会在此创建
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				//若为FactoryBean类型的beanName,会创建两个bean对象
				//&beanName为FactoryBean本身bean对象
				//beanName为FactoryBean实现的getObjectType返回类型,getObject返回对象
				if (isFactoryBean(beanName)) {
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					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);
						}
					}
				}
				//不为FactoryBean则调用getBean获取bean,若获取不到则创建bean
				else {
					getBean(beanName);
				}
			}
		}
		//实现SmartInitializingSingleton的接口后
		//当所有单例 bean 都初始化完成以后
		//Spring的IOC容器会回调该接口的 afterSingletonsInstantiated()方法。
		//bean类中可实现SmartInitializingSingleton接口,自定义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();
				}
			}
		}
	}

getBean 获取bean

getBean方法会调用doGetBean()方法,

	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
		//返回bean名称,规范beanName
		final String beanName = transformedBeanName(name);
		Object bean;

		//先从缓存中取数据
		//spring有3级缓存,用于解决循环依赖
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}
		else {
		//省略部分不重要代码
			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);
				//是否有@dependsOn注解,表示依赖bean,存在则需先创建依赖bean
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
					for (String dep : dependsOn) {
						registerDependentBean(dep, beanName);
						try {
							getBean(dep);
						}
						catch (NoSuchBeanDefinitionException ex) {
						}
					}
				}
				// 判断是否单例,是则调用createBean创建bean
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							//创建失败销毁bean
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
				//省略原型bean代码,每次都创建bean
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}
		//省略部分代码 
		return (T) bean;
	}

doCreateBean 创建bean

createBean方法继续调用AbstractAutowireCapableBeanFactory.doCreateBean()方法,这也是最终创建bean的方法,非常重要。

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {
		BeanWrapper instanceWrapper = null;
		//若为单例,则先移除spring中beanName的bean
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		//实例化对象,此处只是spring选取构造函数反射实例化
		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中的注解信息. 
		//此时对象已经创建出来, 但是spring还没有创建成功, 因为各种属性还未添加.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
				}
				mbd.postProcessed = true;
			}
		}
		//此处用来判断是否在创建,用来解决循环依赖
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}
		Object exposedObject = bean;
		try {
			//填充属性
			populateBean(beanName, mbd, instanceWrapper);
			//初始化
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
		}
		//省略循环依赖代码,后面有专门文章介绍
		return exposedObject;
	}

createBeanInstance 实例化对象

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		Class<?> beanClass = resolveBeanClass(mbd, beanName);
		//省略部分代码
		//调用determineConstructorsFromBeanPostProcessors选择构造方法来创建对象
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}
		//使用默认的构无参造函数
		return instantiateBean(beanName, mbd);
	}

determineConstructorsFromBeanPostProcessors主要是循环所有BeanPostProcessor,调用SmartInstantiationAwareBeanPostProcessor类型的BeanPostProcessor,执行determineCandidateConstructors方法,若有返回值则调用此构造函数。若都没有返回null,使用默认的构无参造函数。

	protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
			throws BeansException {

		if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
					if (ctors != null) {
						return ctors;
					}
				}
			}
		}
		return null;
	}

如何使用有参构造方法来创建对象呢?
有四个判断条件.

  1. 通过上方,后置处理器,找到了唯一的有参构造
  2. BeanDefinition设置为自动创建的模式 AUTOWIRE_CONSTRUCTOR
  3. BeanDefinition我们设置了ConstructorArgumentValues, 还记得mybatis吗? 我们扫描完BeanDefinition后,给BeanDefinition设置使用什么构造参数和使用哪个beanClass.
  4. 调用singletonObject是,传入的args就不为空, 是有值的, 明确告诉你, 我需要构造方法创建.

populateBean 填充属性

	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		boolean continueWithPropertyPopulation = true;
		//调用beanPostProcess, 用来判断你的bean需不需要完成属性填充 ,
		//如果实现此接口返回false,那么spring不会帮我们填充属性.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}
		//返回false直接返回
		if (!continueWithPropertyPopulation) {
			return;
		}
		
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
		//设置自动注入模式,是感觉name还是type
		//默认是 AUTOWIRE_BY_NO.
		if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			pvs = newPvs;
		}
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		//使用后置处理器来处理对象, 例如require , autowire 注解
   		//调用beanPostProcess , InstantiationAwareBeanPostProcessor的postProcessPropertyValues()方法.
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
						}
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse;
				}
			}
		}
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

populateBean方法中主要两次使用beanPostProcessor,第一次用来判断是否需要进行属性填充,第二次用InstantiationAwareBeanPostProcessor的postProcessPropertyValues()方法来具体填充属性。

initializeBean 初始化bean

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

初始化主要执行:
1、initializeBean方法中先调用后置处理器执行@PostConstruct
2、invokeInitMethods中执行InitializingBean接口中afterPropertiesSet方法
3、最后执行我们自定义的init方法
具体操作可见 : Spring系列之生命周期回调链接.

总结

spring创建bean过程相当的复杂,本文挑选主线,列出从容器启动到bean创建完成的主要过程。
主要包含:容器启动、包扫描、生成BeanDefinition、BeanFactoryPostProcessor修改BeanDefinition、选取构造函数、反射实例化对象、填充属性、初始化、aop。

你可能感兴趣的:(spring,spring,java)