spring源码分析——bean的实例化流程

Posted 格物致知

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring源码分析——bean的实例化流程相关的知识,希望对你有一定的参考价值。

 

 

  bean的实例化过程是spring容器启动的核心部分,会把上面已经注册的BeanDefinitionMaps中的非懒加载的对象,全部实例化,这个

过程中包括bean对象的创建、属性的设置、初始化等等。

1:在AbstractApplicationContext类中的refresh方法中有个finishBeanFactoryInitalization

 

 2:预实例化所有的非懒加载的单例bean

 

 

 

 3:预实例化所有的单例bean

	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) {
			logger.trace("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		// 拿到beanDefinitionNames集合中所有的beanName,之前在解析xml或者注解的时候注册进去的
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			// 获取已经merge的RootBeanDefinition对象
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			// 如果beanDefinition不是抽象bean 是单例 且不是懒加载,那么就会实例化
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				// 判断是否FactoryBean类
				if (isFactoryBean(beanName)) {
					// 如果是FactoryBean类型,那么获取bean就需要 &+beanName的形式获取,否则获取的是getObject的实例
					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类
				else {
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		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();
				}
			}
		}
	}

  

该类是DefaultListableBeanFactory,这个是核心的BeanFactory,在refresh中实例返回就是这个beanFactory工厂容器。

 

 

 

 

 

来分析一下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;

		// Eagerly check singleton cache for manually registered singletons.
		// 创建bean之前,检查单例缓存中是否存在手工注册的bean对象
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isTraceEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.trace("Returning eagerly cached instance of singleton bean \'" + beanName +
							"\' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.trace("Returning cached instance of singleton bean \'" + beanName + "\'");
				}
			}
			// 如果缓存中存在,判断是否是FactoryBean类型
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		// 缓存中不存在
		else {
			// Fail if we\'re already creating this bean instance:
			// We\'re assumably within a circular reference.
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			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 if (requiredType != null) {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
				else {
					return (T) parentBeanFactory.getBean(nameToLookup);
				}
			}

			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}

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

				// Guarantee initialization of beans that the current bean depends on.
				// 保证在当前bean初始化之前让dependson的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);
						}
					}
				}

				// Create bean instance.
				// 如果是单例,则创建单例bean
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				// 如果bean的原型模式,非单例,那么就不会缓存对象
				else if (mbd.isPrototype()) {
					// It\'s a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						// 创建bean对象前,将正在创建的beanName缓存,阻断循环依赖
						beforePrototypeCreation(beanName);
						// 创建bean对象,和单例时流程一样,只是不缓存
						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.isTraceEnabled()) {
					logger.trace("Failed to convert bean \'" + name + "\' to required type \'" +
							ClassUtils.getQualifiedName(requiredType) + "\'", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

  

首先根据beanName到缓存中取找

 

 

 

 

具体创建单例bean的方法:

 

 

getSingleton方法:

 

 

创建完成后放入一级缓存中,然后把bean对象返回

 

这是创建的大致流程,下面我们来看一下具体怎么创建的bean

 

 

createBean方法中:

 

 

 

对象创建的具体流程在这个方法中:

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

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		// 创建bean实例,在内存堆中创建一个对象
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					// 在这里CommonAnnotationBeanPostProcessor和AutowiredAnnotationBeanPostProcessor完成类注解信息的收集
					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.
		/**
		 * bean是单例,且允许循环依赖,并且正在创建,那么就会把它先放到三级缓存
		 */
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean \'" + beanName +
						"\' to allow for resolving potential circular references");
			}
			// 把正在创建的bean(还没有初始化)先放到三级缓存中
			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;
	}

  

在内存中创建bean对象:

 

 

设置bean的属性并初始化bean对象:

 

 

初始化完成后,会得到一个exposedObject 可以暴露的bean对象,到这里bean就创建完成了,至于设置属性、依赖注入、循环依赖、初始化等具体

细节,我们在后续章节再来分析。

总结:bean的实例化过程

1:在refresh的最后,会实例化所有的非懒加载的(非lazy-init)的单例bean

2:创建过程,首先会到一级缓存singletonObjects中尝试获取,如果能拿到,说明之前已经创建过,直接返回,不能则创建

3:如果是单例的、非抽象类、非懒加载的,则创建bean对象,在创建之前,会把beanName放入正在创建的容器中标记

4:调用回调放入getObject进行创建工作,主要内容有 在内存堆中创建裸对象、设置对象的属性、初始化对象

5:创建完成后,从正在创建的容器中删除该beanName,然后将exposedObject放入一级缓存中

 

以上是关于spring源码分析——bean的实例化流程的主要内容,如果未能解决你的问题,请参考以下文章

Spring框架进阶Spring V3.0 DI源码分析流程

Spring系列(一)Spring MVC bean 解析、注册、实例化流程源码剖析

Spring源码剖析-单利Bean的实例化

08Spring源码-分析篇-Bean的实例化

浅谈Spring中Bean的生命周期

Spring源码分析原型Bean实例化过程byName与byType及FactoryBean获取Bean源码实现