Spring源码学习07

1.populateBean方法

/**
	 * Populate the bean instance in the given BeanWrapper with the property values
	 * from the bean definition.
	 *
	 * 使用bean定义中的属性值来操作给定BeanWrapper中的bean实例
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param bw the BeanWrapper with bean instance
	 */
	protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		//获取支持Map的propertyValue,从xml中解析到property value配置
		PropertyValues pvs = mbd.getPropertyValues();
		//bean实例为null
		if (bw == null) {
			//属性不为空,但是没有创建bean直接抛出异常
			if (!pvs.isEmpty()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				//跳过属性填充步骤
				return;
			}
		}

		// 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.
		//为任何InstantiationAwareBeanPostProcessors提供在设置属性之前修改bean状态的机会
		//可以用来支持属性注入的类型
		boolean continueWithPropertyPopulation = true;
		//
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					//TODO 是否执行post-processor,如果返回false代表需要对bean进行属性装配,反之退出bean装配
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}
		//如果不填充bean则终止bean的填充
		if (!continueWithPropertyPopulation) {
			return;
		}
		//
		//
		//下面的逻辑会把构造器中需要依赖注入的bean或者需要@Autowired注解或者xml配置autowire为byName或者byType
		// 修饰的bean放到propertyValue中,如果bean依赖的bean还未创建
		//则会在autowireByName或者autowireByType中创建

		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			// 根据名称自动注入逻辑,如果某些依赖的bean没有创建则在这里会被初始化
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			// 根据类型自动注入.如果某些依赖的bean没有创建,则在这里会被初始化
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}
		//是否有InstantiationAwareBeanPostProcessor处理器
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		//是否需要依赖检查
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
		//如果有InstantiationAwareBeanPostProcessor处理器或者需要依赖检查
		if (hasInstAwareBpps || needsDepCheck) {
			//需要进行依赖检查的propertyrDescriptor
			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			if (hasInstAwareBpps) {
				for (BeanPostProcessor bp : getBeanPostProcessors()) {
					if (bp instanceof InstantiationAwareBeanPostProcessor) {
						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
						//TODO 扩展点 所有需要进行依赖检查的属性进行后处理
						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
			}
			if (needsDepCheck) {
				//depends-on属性检查
				checkDependencies(beanName, mbd, filteredPds, pvs);
			}
		}
		//属性应用到bean
		applyPropertyValues(beanName, mbd, bw, pvs);
	}

2.我们可以通过InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法来跳过属性赋值

3.autoByName和autoByType在执行过程中会创建依赖的bean

 4.我们还可以对有InstantiationAwareBeanPostProcessor处理器的工厂或者需要依赖检查的bean进行属性的后置处理

5.应用属性到bean中大致有以下几个步骤

a.判断是否为MutablePropertyValues是的话,判断需不需要converted不需要直接转换

b.获取所有porpertyValues

c.获取coverter

d.处理propertyValue属性,解析map、list、array、runtimeBeanReference

e.判断propertyValue需不需要转换,需要的话会进行covertProperty,

f.保存propertyValue的到deepCopy,用于给bean赋值

g.赋值操作

/**
	 * Apply the given property values, resolving any runtime references
	 * to other beans in this bean factory. Must use deep copy, so we
	 * don't permanently modify this property.
	 *
	 * 应用给定的属性值,解析任何运行时引用
	 * 到这个bean工厂的其他bean。 必须使用深层复制,
	 * 所以我们永远不要修改属性
	 * @param beanName the bean name passed for better exception information
	 * @param mbd the merged bean definition
	 * @param bw the BeanWrapper wrapping the target object
	 * @param pvs the new property values
	 */
	protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		//pvs不存在不需要注入了
		if (pvs == null || pvs.isEmpty()) {
			return;
		}

		if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
			((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
		}
		MutablePropertyValues mpvs = null;
		List<PropertyValue> original;
		//如果是MutablePropertyValues,
		//当bean的属性有通过autowireByName或者autowireByType时
		//pvs就是MutablePropertyValues
		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			//判断是否转换过了,转换过了直接setPropertyValues
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			//获取propertyValues集合
			original = mpvs.getPropertyValueList();
		}
		else {
			original = Arrays.asList(pvs.getPropertyValues());
		}
		//获取类型转换器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}
		//值解析器
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		// Create a deep copy, resolving any references for values.
		//将值引用保存到deepCopy 中
		List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
		boolean resolveNecessary = false;
		//循环处理
		for (PropertyValue pv : original) {
			if (pv.isConverted()) {
				deepCopy.add(pv);
			}
			else {
				//属性名称
				String propertyName = pv.getName();
				//值
				Object originalValue = pv.getValue();
				//解析value,比如value可能为map、list、runtimeBean类型
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;
				//property是否可写-->其实就是判断属性是否存在
				//判断参数是否为index 或者嵌套比如属性为["name1","name2"];
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					//进行value转换操作
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				//可以在合并的bean定义中存储转换后的值,以避免每个创建的bean实例重新转换。
				if (resolvedValue == originalValue) {
					if (convertible) {
						//设置pv的转换后的值
						pv.setConvertedValue(convertedValue);
					}
					deepCopy.add(pv);
				}
				//能转换并且原始值类型为TypedStringValue并且originalValue不是动态的
				//并且转换的后的属性不是Collection的子类或者数组
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				}
				else {
					//其他情况判定,还有必要进行resolve
					resolveNecessary = true;
					deepCopy.add(new PropertyValue(pv, convertedValue));
				}
			}
		}
		//如果mpvs不为null并且需要不转换
		if (mpvs != null && !resolveNecessary) {
			mpvs.setConverted();
		}

		// Set our (possibly massaged) deep copy.
		try {
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}

6.对于convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);方法,有必要了解下PropertyEditor到底怎么用的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值