首页 > 编程语言 >Spring源码-autowireByType

Spring源码-autowireByType

时间:2022-10-01 15:44:33浏览次数:60  
标签:String autowireByType Spring propertyName beanName bean 源码 bw 属性

autowireByType

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[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
	for (String propertyName : propertyNames) {
		try {
			PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
			// Don't try autowiring by type for type Object: never makes sense,
			// even if it technically is a unsatisfied, non-simple property.
			if (Object.class != pd.getPropertyType()) {
				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);
				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. 获取bw中有setter方法 且 非简单类型属性 且 mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组

  2. 遍历属性名数组,通过属性类型从bean工厂中选取出bean,同时解析出bean的依赖bean,如果能通过类型获取到bean则将属性名和属性值注册到pvs,如果存在依赖bean,则将依赖bean注册到bean工厂。

标签:String,autowireByType,Spring,propertyName,beanName,bean,源码,bw,属性
From: https://www.cnblogs.com/shigongp/p/16747132.html

相关文章