一起学SF框架系列5.5-模块Beans-AbstractAutowireCapableBeanFactory

AbstractAutowireCapableBeanFactory继承于AbstractBeanFactory,主要负责bean创建后的相关处理,包括属性、装配、初始化等等。

类作用

AbstractAutowireCapableBeanFactory提供bean创建(构造函数带参)、属性填充、连接(包括自动连接)和初始化。处理运行时bean引用、解析托管集合、调用初始化方法等。支持自动连接构造函数、按名称的属性和按类型的属性。

类实现

createBean

实际创建bean的入口,通过重载适应多种情况,主体在Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

	/* 按类型创建bean,用于SCOPE_PROTOTYPE */
	@Override
	@SuppressWarnings("unchecked")
	public <T> T createBean(Class<T> beanClass) throws BeansException {
		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd = new CreateFromClassBeanDefinition(beanClass);
		bd.setScope(SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader());
		return (T) createBean(beanClass.getName(), bd, null);
	}
	/* 自动装配模式下创建bean */
	@Override
	public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
		bd.setScope(SCOPE_PROTOTYPE);
		return createBean(beanClass.getName(), bd, null);
	}

核心方法-createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

实例化bean的主体实现:创建一个bean实例,填充bean实例,应用后处理器等

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

		if (logger.isTraceEnabled()) {
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;

		/* 加载bean的类文件。如果传入mbd原来没有beanClass,则复制mbd到mbdToUse,并把获取的beanClass赋值给mbdToUse.beanClass(不改变mbd现状) 注1 */
		// Make sure bean class is actually resolved at this point, and
		// clone the bean definition in case of a dynamically resolved Class
		// which cannot be stored in the shared merged bean definition.
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		//检查该Override的方法bean是否全部都有实现
		// Prepare method overrides.
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			/*如果有实现了InstantiationAwareBeanPostProcessor接口的bean,且在其中创建了要生成的bean,直接返回,且后续框架针对bean的初始化过程均不执行 */
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
			//spring实例化bean
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			// A previously detected exception with proper bean creation context already,
			// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}

注1:resolveBeanClass见AbstractBeanFactory实现https://blog.csdn.net/davidwkx/article/details/130963899

resolveBeforeInstantiation

如果应用实现接口BeanPostProcessor,且有对当前bean实例化有自己实现,返回实现的bean

	protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		//?为啥不直接用:if (mbd.beforeInstantiationResolved)
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				//确定mbd定义bean同要beanName代表的bean是一致的
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
					//调用postProcessBeforeInstantiation生成bean
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						//如果postProcessBeforeInstantiation没产生bean,调用postProcessAfterInstantiation生成bean
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}

doCreateBean

创建bean前的工作全部完成,本方法实际创建一个指定的bean。

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

		//bean封装器 注1
		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			 //单实例模式下,有可能该Bean创建之前就已经被创建出来了(比如在依赖注入过程中)。如果是这样,从bean实例工厂缓存删除
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			//创建一个新的bean实例
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		//取出bean对象
		Object bean = instanceWrapper.getWrappedInstance();
		//取beanType
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		/* 用MergedBeanDefinitionPostProcessor(扩展点)修改设置属性 */
		// Allow post-processors to modify the merged bean definition.
		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已执行
				mbd.markAsPostProcessed();
			}
		}

		// 提前检测循环依赖:单例&允许循环依赖&当前bean正在创建中
		// 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.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			// 为避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂缓存池,从早期工厂缓存池删除
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		//初始化bean实例(进行相关属性设置)
		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			// 对bean的属性进行填充,将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean
			populateBean(beanName, mbd, instanceWrapper);
			// 执行初始化逻辑: 应用工厂回调、init方法和bean后处理器
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException bce && beanName.equals(bce.getBeanName())) {
				throw bce;
			}
			else {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName, ex.getMessage(), ex);
			}
		}

		//处理循环依赖情况
		if (earlySingletonExposure) {
			//从缓存中获取bean对象
			Object earlySingletonReference = getSingleton(beanName, false);
			// earlySingletonReference只有在检测到有循环依赖的情况下才会不为空
			if (earlySingletonReference != null) {
				//初始化的bean-exposedObject 同从缓存中获得的bean是否相同
				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) {
						//如果对应bean名称的实例仅用于类型检查就删除它,否则就表示还用于其它目的
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							//用于其它目的bean名称加入到actualDependentBeans
							actualDependentBeans.add(dependentBean);
						}
					}
					// 因为bean创建后所依赖的bean一定是已经创建的,actualDependentBeans不为空则表示当前bean创建后其依赖的bean却没有全部创建完,也就是说存在循环依赖
					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 " +
								"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// 注册销毁bean列表,便于销毁对象
		// 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:BeanWrapper -bean的封装器,提供分析和操作标准JavaBeans的操作:能够获取和设置属性值(单独或批量)、获取属性描述符以及查询属性的可读性/可写性。

createBeanInstance

创建beand的一个新实例,创建方式有很多种,包括:生产者、工厂方法、构造函数自动装配或正常实例化等。

	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		//确保beanClass已被加载
		// Make sure bean class is actually resolved at this point.
		Class<?> beanClass = resolveBeanClass(mbd, beanName);
		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}

		//如果bean是生产者(Supplier)提供的,则直接由生产者提供bean对象
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName, mbd);
		}
		
		//如果bean是工厂方法生成,例如:@Bean注解放在方法上/xml: factory-method,返回值注入容器,spring 会认为这是一个工厂方法 注1
		if (mbd.getFactoryMethodName() != null) {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}
		
		/* spring会将解析过后确定下来的构造器或工厂方法缓存到mbd中resolvedConstructorOrFactoryMethod字段中。下次创建相同bean时直接从缓存的值获取,加快创建过程*/
		// Shortcut when re-creating the same bean...
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) {
				//构造函数自动注入
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				// 使用默认构造函数构造
				return instantiateBean(beanName, mbd);
			}
		}

		//用自动装配构建器创建bean: 从bean后置处理器中为自动装配寻找构造方法, 有且仅有一个有参构造或者有且仅有@Autowired注解构造
		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		// 以下情况符合其一即可进入
		// 1、存在可选构造方法
		// 2、构造函数为自动装配模式
		// 3、BeanDefinition中有构造参数值
		// 4、有构造函数参数列表的参数
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		//用高优先级的构造器创建bean
		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		//默认使用无参构造器创建bean
		// No special handling: simply use no-arg constructor.
		return instantiateBean(beanName, mbd);
	}

注1:instantiateUsingFactoryMethod实际实现在ConstructorResolver.instantiateUsingFactoryMethod,详见https://blog.csdn.net/davidwkx/article/details/131047724

populateBean

设置bean属性

	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		if (bw == null) {
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

		//bean不是java.lang.Record类型
		if (bw.getWrappedClass().isRecord()) {
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to a record");
			}
			else {
				// Skip property population phase for records since they are immutable.
				return;
			}
		}

		//属性设置前,如果有InstantiationAwareBeanPostProcessors实现,就按此处理,直接返回
		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
				if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					return;
				}
			}
		}

		/* 获取bean属性集,对每个属性进行初始化 */
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
		//属性设置方式
		int resolvedAutowireMode = mbd.getResolvedAutowireMode();
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			/*按名称或类型装配 */
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// Add property values based on autowire by name if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			pvs = newPvs;
		}
		//属性设置后,如果有InstantiationAwareBeanPostProcessors实现,就执行
		if (hasInstantiationAwareBeanPostProcessors()) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
				//调用postProcessProperties实现对属性设置
				PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
				if (pvsToUse == null) {
					return;
				}
				pvs = pvsToUse;
			}
		}

		/*执行相关性检查,以确保已设置所有公开的属性。*/
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
		if (needsDepCheck) {
			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			//依赖关系检查包括对象(协作bean)、简单类型(如字符串)
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		if (pvs != null) {
			//把pvs中的属性值,采用深度复制,解析到运行期bean对其它bean引用。
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

autowireByName/autowireByType

按名称或类型装配bean属性。

	protected void autowireByName(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		//查找未处理的且非简单类型(指String等java基本类型)的属性
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			if (containsBean(propertyName)) {
				//获取bean(来源于属性依赖关系进行的bean创建)
				Object bean = getBean(propertyName);
				//建立属性和bean关系
				pvs.add(propertyName, bean);
				//注册依赖关系
				registerDependentBean(propertyName, beanName);
				if (logger.isTraceEnabled()) {
					logger.trace("Added autowiring by name from bean name '" + beanName +
							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
							"' by name: no matching bean found");
				}
			}
		}
	}

	protected void autowireByType(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		//获取类型转换器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}

		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
		//查找未处理的且非简单类型(指String等java基本类型)的属性
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			try {
				//获取属性的PropertyDescriptor 
				PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
				// Don't try autowiring by type for type Object: never makes sense,
				// even if it technically is an unsatisfied, non-simple property.
				//属性是Object类型,而Obejct是java根类,无确定意义,无需装配
				if (Object.class != pd.getPropertyType()) {
					//获取属性相关的set方法
					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
					// Do not allow eager init for type matching in case of a prioritized post-processor.
					boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
					// 解析指定beanName对应的属性,并将解析到的属性名放入autowiredBeanNames,根据类型查找依赖关系 注1
					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
					if (autowiredArgument != null) {
						pvs.add(propertyName, autowiredArgument);
					}
					for (String autowiredBeanName : autowiredBeanNames) {
						registerDependentBean(autowiredBeanName, beanName);
						if (logger.isTraceEnabled()) {
							logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
									propertyName + "' to bean named '" + autowiredBeanName + "'");
						}
					}
					autowiredBeanNames.clear();
				}
			}
			catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
			}
		}
	}

注1:resolveDependency 实现见子类DefaultListableBeanFactory.resolveDependency ,详见:https://blog.csdn.net/davidwkx/article/details/130715587

applyPropertyValues

把pvs中的属性值,采用深度复制,解析到运行期bean对其它bean引用。

	protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		if (pvs.isEmpty()) {
			return;
		}

		MutablePropertyValues mpvs = null;
		//记录原始属性值列表
		List<PropertyValue> original;
		//pvs是MutablePropertyValues 类型
		if (pvs instanceof MutablePropertyValues _mpvs) {
			mpvs = _mpvs;
			if (mpvs.isConverted()) {
				//mpvs只包含转换后的值
				// Shortcut: use the pre-converted values as-is.
				try {
					//使用mpvs批量设置bw包装的Bean对象属性,然后直接结束
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			//获取mpvs的PropertyValue对象列表
			original = mpvs.getPropertyValueList();
		}
		else {
			//获取pvs的PropertyValue对象列表
			original = Arrays.asList(pvs.getPropertyValues());
		}

		获取工厂的自定义类型转换器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			//使用bw作为转换器
			converter = bw;
		}
		//在bean工厂实现中使用Helper类-bean定义值解析器,它将beanDefinition对象中包含的值解析为应用于目标bean实例的实际值
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		//创建一个深拷贝,解析任何值引用
		// Create a deep copy, resolving any references for values.
		List<PropertyValue> deepCopy = new ArrayList<>(original.size());
		boolean resolveNecessary = false;
		for (PropertyValue pv : original) {
			if (pv.isConverted()) {
				//pv已转换值
				deepCopy.add(pv);
			}
			else {
				String propertyName = pv.getName();
				Object originalValue = pv.getValue();
				//如果originalValue 值是AutowiredPropertyMarker标记
				if (originalValue == AutowiredPropertyMarker.INSTANCE) {
					//基于propertyName获取在bw中的setter方法
					Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
					if (writeMethod == null) {
						throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
					}
					//将writerMethod封装到DependencyDescriptor对象
					originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
				}
				//由值解析器解析出originalValue所封装的对象
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				//默认转换后的值是刚解析出来的值
				Object convertedValue = resolvedValue;
				//可转换标记: bw可写 && prepertyName不是表示索引属性或嵌套属性
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					//将resolvedValue按属性类型转换
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				// 可以将转换后的值存储合并后BeanDefinition中,以避免对每个创建的Bean实例进行重新转换
				//如果resolvedValue与originalValue是同一个对象
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				if (resolvedValue == originalValue) {
					if (convertible) {
						//将resolvedValue按属性类型转换
						pv.setConvertedValue(convertedValue);
					}
					//将pv添加到deepCopy中
					deepCopy.add(pv);
				}
				//TypedStringValue:类型字符串的Holder,这个holder将只存储字符串值和目标类型。实际得转换将由Bean工厂执行
				//如果可转换 && originalValue是TypedStringValue的实例 && orginalValue不是标记为动态【即不是一个表达式】&&
				// 	convertedValue不是Collection对象 或 数组
				else if (convertible && originalValue instanceof TypedStringValue typedStringValue &&
						!typedStringValue.isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					//将convertedValue设置到pv中
					pv.setConvertedValue(convertedValue);
					//将pv添加到deepCopy中
					deepCopy.add(pv);
				}
				else {
					resolveNecessary = true;
					//根据pv,convertedValue构建PropertyValue对象,并添加到deepCopy中
					deepCopy.add(new PropertyValue(pv, convertedValue));
				}
			}
		}
		if (mpvs != null && !resolveNecessary) {
			//设置转换标记
			mpvs.setConverted();
		}

		// Set our (possibly massaged) deep copy.
		try {
			//以deepCopy构造一个新的MutablePropertyValues对象,然后设置到bw中对应的属性
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, ex.getMessage(), ex);
		}
	}

initializeBean

初始化给定的bean实例:应用工厂回调以及init方法和bean后处理器

	protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		//初始化第1步:调用实现Aware的bean,设置对应属性
		invokeAwareMethods(beanName, bean);

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			//初始化第2步:如果有则调用BeanPostProcessorsBeforeInitialization
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			//初始化第3步:调用实现接口InitializingBean或了自定义init方法的bean
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null), beanName, ex.getMessage(), ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			//初始化第4步:如果有则调用BeanPostProcessorsBeforeInitialization
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

invokeAwareMethods

初始化的第一步就是执行实现Aware接口的bean,此处只执行三类Aware Bean:BeanNameAware 、BeanClassLoaderAware 、BeanFactoryAware 。

	private void invokeAwareMethods(String beanName, Object bean) {
		if (bean instanceof Aware) {
			// beanNameAware处理
			if (bean instanceof BeanNameAware beanNameAware) {
				beanNameAware.setBeanName(beanName);
			}
			// beanClassLoaderAware处理
			if (bean instanceof BeanClassLoaderAware beanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					beanClassLoaderAware.setBeanClassLoader(bcl);
				}
			}
			// beanFactoryAware处理
			if (bean instanceof BeanFactoryAware beanFactoryAware) {
				beanFactoryAware.setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}

applyBeanPostProcessorsBeforeInitialization / applyBeanPostProcessorsAfterInitialization

如果有实现BeanPostProcessor接口,则执行postProcessBeforeInitialization或postProcessAfterInitialization。

	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException {
		
		Object result = existingBean;
		//逐一对每个BeanPostProcessor实现bean调用postProcessBeforeInitialization
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			//注意:上一个BeanPostProcessor bean的行结果Bean是执行下一个的参数Object 
			Object current = processor.postProcessBeforeInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		//返回结果是经过所有BeanPostProcessor Bean处理后的bean
		return result;
	}

	@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		//逐一对每个BeanPostProcessor实现bean调用postProcessAfterInitialization
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			//注意:上一个BeanPostProcessor bean的行结果Bean是执行下一个的参数Object 
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		//返回结果是经过所有BeanPostProcessor Bean处理后的bean
		return result;
	}

invokeInitMethods

执行初始化方法,包括bean实现InitializingBean接口afterPropertiesSet或配置了初始化方法。

	protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {

		boolean isInitializingBean = (bean instanceof InitializingBean);
		//实现了InitializingBean接口afterPropertiesSet,直接执行
		if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {
			if (logger.isTraceEnabled()) {
				logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
			}
			((InitializingBean) bean).afterPropertiesSet();
		}

		if (mbd != null && bean.getClass() != NullBean.class) {
			String[] initMethodNames = mbd.getInitMethodNames();
			//配置了初始化方法的bean(@PreConstruct或xml模式init-method),直接执行
			if (initMethodNames != null) {
				for (String initMethodName : initMethodNames) {
					if (StringUtils.hasLength(initMethodName) &&
							//不是InitializingBean
							!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
							//不是外部管理的init方法
							!mbd.hasAnyExternallyManagedInitMethod(initMethodName)) {
						//用反射机制执行初始化方法
						invokeCustomInitMethod(beanName, bean, mbd, initMethodName);
					}
				}
			}
		}
	}

invokeCustomInitMethod

用反射机制执行init方法

	protected void invokeCustomInitMethod(String beanName, Object bean, RootBeanDefinition mbd, String initMethodName)
			throws Throwable {

		//取方法(方法存在且必须可访问)
		Method initMethod = (mbd.isNonPublicAccessAllowed() ?
				BeanUtils.findMethod(bean.getClass(), initMethodName) :
				ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

		//方法不存在
		if (initMethod == null) {
			if (mbd.isEnforceInitMethod()) {
				throw new BeanDefinitionValidationException("Could not find an init method named '" +
						initMethodName + "' on bean with name '" + beanName + "'");
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("No default init method named '" + initMethodName +
							"' found on bean with name '" + beanName + "'");
				}
				// Ignore non-existent default lifecycle methods.
				return;
			}
		}

		if (logger.isTraceEnabled()) {
			logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
		}

		//缓存initMethod,确定接口方法
		Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod, bean.getClass());

		try {
			//反射机制执行方法
			ReflectionUtils.makeAccessible(methodToInvoke);
			methodToInvoke.invoke(bean);
		}
		catch (InvocationTargetException ex) {
			throw ex.getTargetException();
		}
	}

你可能感兴趣的:(Spring学习系列,java,开发语言)