Spring属性填充populateBean源码分析

一,属性填充分类

Spring实例化前面我们已经分析过了,实例化之后,紧接着就是对属性进行填充了,属性填充主要是对自动注入(autowired)的处理,我们大致可以把他分为三类:

  1. autowireByName:通过名字对属性填充。
  2. autowireByType:通过类型对属性填充。
  3. @Autowired:通过bean的后置处理器AutowiredAnnotationBeanPostProcessor对@Autowired注解属性填充

我们来看一下具体源码:

	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    
    
	
    	// 省略部分代码.......
    
		// 获取 mbd 的 自动装配模式
		int resolvedAutowireMode = mbd.getResolvedAutowireMode();
		// 如果 自动装配模式 为 按名称自动装配bean属性 或者 按类型自动装配bean属性
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
    
    
			/**
			 *	1,根据属性名进行注入
			 */
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
    
    
				//通过bw的PropertyDescriptor属性名,查找出对应的Bean对象,将其添加到newPvs中
				autowireByName(beanName, mbd, bw, newPvs);
			}
			
			/**
			 *	2,根据属性类型进行注入
			 */
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
    
    
				//通过bw的PropertyDescriptor属性类型,查找出对应的Bean对象,将其添加到newPvs中
				autowireByType(beanName, mbd, bw, newPvs);
			}
			
		}

			
			/**
			 *	3,通过遍历到AutowiredAnnotationBeanPostProcessor执行postProcessProperties()方法
			 *	来实现对@Autowired注解进行注入
			 */
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
    
    
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
    
    
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					
				}
			}
		}

		// 上面只是把属性所对应得object保存到pvs中,并没有给属性赋值
		// 这里会调用类得set方法给属性赋值
		if (pvs != null) {
    
    
			//应用给定的属性值,解决任何在这个bean工厂运行时其他bean的引用。必须使用深拷贝,所以我们 不会永久地修改这个属性
			applyPropertyValues(beanName, mbd, bw, pvs);
		}

		// 省略部分代码...
	}

二,autowireByName通过名字对属性填充

定义person然后指定byName注入:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="person" class="com.bobo.selfAutowired.Person" autowire="byName"></bean>
</beans>

AbstractAutowireCapableBeanFactory#populateBean():完成属性得自动注入。通过属性得name找到对应得obj对象,保存到pvs的propertyValueList里面,然后再遍历propertyValueList,通过反射调用当前对象得set方法给属性赋值。

	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    
    
        
    // 省略部分代码....
        
	if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
    
    
		//通过bw的PropertyDescriptor属性名,查找出对应的Bean对象,将其添加到newPvs中
		autowireByName(beanName, mbd, bw, newPvs);
	}

	// 上面只是把属性所对应得object保存到pvs中,并没有给属性赋值
	// 这里会调用类得set方法给属性赋值
	if (pvs != null) {
    
    
		//应用给定的属性值,解决任何在这个bean工厂运行时其他bean的引用。必须使用深拷贝,所以我们 不会永久地修改这个属性
		applyPropertyValues(beanName, mbd, bw, pvs);
	}

	// 省略部分代码...
}

AbstractAutowireCapableBeanFactory#autowireByName():获取当前beanName得非简单类型属性名,并且遍历这些属性名,能在容器中找到当前属性名得对象,则添加到pvs的propertyValueList中。

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

		//获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		//遍历属性名
		for (String propertyName : propertyNames) {
    
    
			//如果该bean工厂有propertyName的beanDefinition或外部注册的singleton实例
			if (containsBean(propertyName)) {
    
    
				//获取该工厂中propertyName的bean对象
				Object bean = getBean(propertyName);
				//将propertyName,bean添加到pvs中
				pvs.add(propertyName, bean);
				//注册propertyName与beanName的依赖关系
				registerDependentBean(propertyName, beanName);
				
			}
		}
	}

AbstractAutowireCapableBeanFactory#unsatisfiedNonSimpleProperties():遍历所有属性值,获取非简单类型的属性名数组并且返回。

protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
    
    
		//TreeSet:TreeSet底层是二叉树,可以对对象元素进行排序,但是自定义类需要实现comparable接口,重写comparaTo()方法。
		Set<String> result = new TreeSet<>();
		//获取mdbd的所有属性值
		PropertyValues pvs = mbd.getPropertyValues();
		//PropertyDescriptor:表示JavaBean类通过存储器导出一个属性,获取bw的所有属性描述对象
		PropertyDescriptor[] pds = bw.getPropertyDescriptors();
		//遍历属性描述对象
		for (PropertyDescriptor pd : pds) {
    
    
			//如果 pd有写入属性方法 && 该pd不是被排除在依赖项检查之外 && pvs没有该pd的属性名 && pd的属性类型不是"简单值类型"
			if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
					!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
    
    
				//将pdd的属性名添加到result中
				result.add(pd.getName());
			}
		}
		//将result装换成数组
		return StringUtils.toStringArray(result);
	}

BeanUtils#isSimpleProperty():返回当前属性类型是否是简单类型:

	public static boolean isSimpleProperty(Class<?> type) {
    
    
		return isSimpleValueType(type) || (type.isArray() && isSimpleValueType(type.getComponentType()));
	}

	public static boolean isSimpleValueType(Class<?> type) {
    
    
		return (Void.class != type && void.class != type &&
				(ClassUtils.isPrimitiveOrWrapper(type) ||
				Enum.class.isAssignableFrom(type) ||
				CharSequence.class.isAssigna总结:autowireByName主要完成以下逻辑:bleFrom(type) ||
				Number.class.isAssignableFrom(type) ||
				Date.class.isAssignableFrom(type) ||
				Temporal.class.isAssignableFrom(type) ||
				URI.class == type ||
				URL.class == type ||
				Locale.class == type ||
				Class.class == type));
	}

总结:autowireByName主要完成以下逻辑:

  1. 获取需要填充对象得非简单类型得属性名;
  2. 遍历第一步获取得属性名,调用getBean方法从容器中获取此属性名对应的object;
  3. 然后,如果能找到,则把此属性名和object对象保存到pvs的propertyValueList里面。

三,autowireByType:通过类型对属性填充

applicationContext.xml:定义person中的属性通过byType自动注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="person" class="com.bobo.selfAutowired.Person" autowire="byType"></bean>
</beans>

AbstractAutowireCapableBeanFactory#populateBean():完成属性的自动注入,通过bw的PropertyDescriptor属性类型,查找出对应的Bean对象,将其添加到pvs的propertyValueList中,然后遍历propertyValueList通过反射调用当前对象得set方法给属性赋值。

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    
    
        
    // 省略部分代码....
        
	if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
    
    
		//通过bw的PropertyDescriptor属性类型,查找出对应的Bean对象,将其添加到newPvs中
		autowireByType(beanName, mbd, bw, newPvs);
	}

	// 上面只是把属性所对应得object保存到pvs中,并没有给属性赋值
	// 这里会调用类得set方法给属性赋值
	if (pvs != null) {
    
    
		//应用给定的属性值,解决任何在这个bean工厂运行时其他bean的引用。必须使用深拷贝,所以我们 不会永久地修改这个属性
		applyPropertyValues(beanName, mbd, bw, pvs);
	}

	// 省略部分代码...
}

AbstractAutowireCapableBeanFactory#autowireByType():

  1. 获取当前对象的非简单类型的属性名数组propertyNames;
  2. 遍历属性名数组propertyNames,获取当前属性名多对应的类型filedType;
  3. 通过filedType找到匹配的候选Bean对象;
  4. 把属性名以及bean对象添加到pvs的propertyValueList里面。
	protected void autowireByType(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    
    

		//获取工厂的自定义类型转换器
		TypeConverter converter = getCustomTypeConverter();
		//如果没有配置自定义类型转换器
		if (converter == null) {
    
    
			//使用bw作为类型转换器
			converter = bw;
		}
		//存放所有候选Bean名的集合
		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
		//获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		//遍历属性名数组
		for (String propertyName : propertyNames) {
    
    
			try {
    
    
				//PropertyDescriptor:表示JavaBean类通过存储器导出一个属性
				//从bw中获取propertyName对应的PropertyDescriptor
				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.
				// 不要尝试按类型自动装配对象:永远是有意义的,即使它在技术上是一个不满意,复杂属性
				//如果pd的属性值类型不是 Object
				if (Object.class != pd.getPropertyType()) {
    
    
					//获取pd属性的Setter方法的方法参数包装对象
					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
					// Do not allow eager init for type matching in case of a prioritized post-processor.
					//判断bean对象是否是PriorityOrder实例,如果不是就允许急于初始化来进行类型匹配。
					//eager为true时会导致初始化lazy-init单例和由FactoryBeans(或带有"factory-bean"引用的工厂方法)创建 的对象以进行类型检查
					boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
					//AutowireByTypeDependencyDescriptor:根据类型依赖自动注入的描述符,重写了 getDependencyName() 方法,使其永远返回null
					//将 methodParam 封装包装成AutowireByTypeDependencyDescriptor对象
					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
					//根据据desc的依赖类型解析出与descriptor所包装的对象匹配的候选Bean对象
					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
					//如果autowiredArgument不为null
					if (autowiredArgument != null) {
    
    
						//将proeprtyName.autowireArgument作为键值添加到pvs中
						pvs.add(propertyName, autowiredArgument);
					}
					//遍历所有候选Bean名集合
					for (String autowiredBeanName : autowiredBeanNames) {
    
    
						//注册beanName与dependentBeanNamed的依赖关系
						registerDependentBean(autowiredBeanName, beanName);
						//打印跟踪日志
						if (logger.isTraceEnabled()) {
    
    
							logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
									propertyName + "' to bean named '" + autowiredBeanName + "'");
						}
					}
					//将候选Bean名集合清空
					autowiredBeanNames.clear();
				}
			}
			catch (BeansException ex) {
    
    
				//捕捉自动装配时抛出的Bean异常,重新抛出 不满足依赖异常
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
			}
		}
	}

DefaultListableBeanFactory#resolveDependency():根据注入属性的类型descriptor.getDependencyType(),去找合适的对象。

	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    
    

		//获取工厂的参数名发现器,设置到descriptor中。使得descriptor初始化基础方法参数的参数名发现。此时,该方法实际上
		// 并没有尝试检索参数名称;它仅允许发现再应用程序调用getDependencyName时发生
		descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
		//如果descriptor的依赖类型为Optional类
		if (Optional.class == descriptor.getDependencyType()) {
    
    
			//创建Optional类型的符合descriptor要求的候选Bean对象
			return createOptionalDependency(descriptor, requestingBeanName);
		}
		// 是对象工厂类型或者对象提供者
		else if (ObjectFactory.class == descriptor.getDependencyType() ||
				ObjectProvider.class == descriptor.getDependencyType()) {
    
    
			//DependencyObjectProvider:依赖对象提供者,用于延迟解析依赖项
			//新建一个DependencyObjectProvider的实例
			return new DependencyObjectProvider(descriptor, requestingBeanName);
		}
		// javaxInjectProviderClass有可能导致空指针,不过一般情况下,我们引用Spirng包的时候都有引入该类以防止空旨在
		//如果依赖类型是javax.inject.Provider类。
		else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
    
    

			//Jse330Provider:javax.inject.Provider实现类.与DependencyObjectProvoid作用一样,也是用于延迟解析依赖
			// 	项,但它是使用javax.inject.Provider作为依赖 对象,以减少与Springd耦合
			//新建一个专门用于构建javax.inject.Provider对象的工厂来构建创建Jse330Provider对象
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
		}
		else {
    
    
			//尝试获取延迟加载代理对象
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			//如果result为null,即表示现在需要得到候选Bean对象
			if (result == null) {
    
    
				//解析出与descriptor所包装的对象匹配的候选Bean对象
				result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
			}
			//将与descriptor所包装的对象匹配的候选Bean对象【result】返回出去
			return result;
		}
	}

DefaultListableBeanFactory#doResolveDependency():根据属性类型去查找合适的候选bean对象。

  1. 首先考虑以下预先解决的信息尝试调用该工厂解决这种依赖关系的快捷方式来获取beanName对应的bean对象;
  2. 尝试使用descriptor的默认值作为最近候选Bean对象;
  3. 针对类型是 stream,数组,Collection类型且对象类型是接口,Map类型 进行解析与依赖类型匹配的 候选Bean对象;
  4. 查找与type匹配的候选bean对象;
  5. 如果以上都没找到,则抛出异常。
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    
    

		//设置新得当前切入点对象,得到旧的当前切入点对象
		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {
    
    
			/**
			 * 1,考虑一些预先解决的信息尝试调用该工厂解决这种依赖关系的快捷方式来获取beanName对应的bean对象,默认返回null
			 */
			Object shortcut = descriptor.resolveShortcut(this);
			if (shortcut != null) {
    
    
				return shortcut;
			}

			//获取descriptor的依赖类型
			Class<?> type = descriptor.getDependencyType();
            
			/**
			 * 2,尝试使用descriptor的默认值作为最近候选Bean对象
			 */
			Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
			//如果默认值不为null
			if (value != null) {
    
    
				//如果value是String类型
				if (value instanceof String) {
    
    
					//解析嵌套的值(如果value是表达式会解析出该表达式的值)
					String strVal = resolveEmbeddedValue((String) value);
					//获取beanName的合并后RootBeanDefinition
					BeanDefinition bd = (beanName != null && containsBean(beanName) ?
							getMergedBeanDefinition(beanName) : null);
					//评估bd中包含的value,如果strVal是可解析表达式,会对其进行解析.
					value = evaluateBeanDefinitionString(strVal, bd);
				}
				//如果没有传入typeConverter,则引用工厂的类型转换器
				TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
				try {
    
    
					//将value转换为type的实例对象
					return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
				}
				//捕捉 不支持操作异常
				catch (UnsupportedOperationException ex) {
    
    
					// A custom TypeConverter which does not support TypeDescriptor resolution...
					return (descriptor.getField() != null ?
							converter.convertIfNecessary(value, type, descriptor.getField()) :
							converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
				}
			}

			
            /**
             * 3,针对desciptor所包装的对象类型是[stream,数组,Collection类型且对象类型是接口,Map]
             * 的情况,进行解析与依赖类型匹配的 候选Bean对象,并将其封装成相应的依赖类型对象
             */
			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
			//如果multpleBeans不为null
			if (multipleBeans != null) {
    
    
				//将multipleBeans返回出去
				return multipleBeans;
			}

			/**
			 * 4,查找与type匹配的候选bean对象,构建成Map,key=bean名,val=Bean对象
			 */
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			//如果没有候选bean对象
			if (matchingBeans.isEmpty()) {
    
    
				//如果descriptor需要注入
				if (isRequired(descriptor)) {
    
    
					//抛出NoSuchBeanDefinitionException或BeanNotOfRequiredTypeException以解决不可 解决的依赖关系
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				//返回null,表示么有找到候选Bean对象
				return null;
			}

			//定义用于存储唯一的候选Bean名变量
			String autowiredBeanName;
			//定义用于存储唯一的候选Bean对象变量
			Object instanceCandidate;

			//如果候选Bean对象Map不止有一个
			if (matchingBeans.size() > 1) {
    
    
				//确定candidates中可以自动注入的最佳候选Bean名称
				autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
				//如果autowiredBeanName为null
				if (autowiredBeanName == null) {
    
    
					//descriptor需要注入 或者 type不是数组/集合类型
					if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
    
    
						//让descriptor尝试选择其中一个实例,默认实现是抛出NoUniqueBeanDefinitionException.
						return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
					}
					else {
    
    
						// In case of an optional Collection/Map, silently ignore a non-unique case:
						// possibly it was meant to be an empty collection of multiple regular beans
						// (before 4.3 in particular when we didn't even look for collection beans).
						// 如果是可选的Collection/Map,则静默忽略一个非唯一情况:
						// 可能是多个常规bean的空集合
						// (尤其是在4.3之前,设置在我们没有寻找collection bean的时候 )
						return null;
					}
				}
				//获取autowiredBeanName对应的候选Bean对象
				instanceCandidate = matchingBeans.get(autowiredBeanName);
			}
			else {
    
    
				// We have exactly one match.
				//这个时候matchingBeans不会没有元素的,因为前面已经检查了
				//获取machingBeans唯一的元素
				Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
				//让autowireBeanName引用该元素的候选bean名
				autowiredBeanName = entry.getKey();
				//让instanceCandidate引用该元素的候选bean对象
				instanceCandidate = entry.getValue();
			}

			//如果候选bean名不为null,
			if (autowiredBeanNames != null) {
    
    
				//将autowiredBeanName添加到autowiredBeanNames中,又添加一次
				autowiredBeanNames.add(autowiredBeanName);
			}
			//如果instanceCandidate是Class实例
			if (instanceCandidate instanceof Class) {
    
    
				//让instanceCandidate引用 descriptor对autowiredBeanName解析为该工厂的Bean实例
				instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
			}
			//定义一个result变量,用于存储最佳候选Bean对象
			Object result = instanceCandidate;
			//如果reuslt是NullBean的实例
			if (result instanceof NullBean) {
    
    
				//如果descriptor需要注入
				if (isRequired(descriptor)) {
    
    
					//抛出NoSuchBeanDefinitionException或BeanNotOfRequiredTypeException以解决不可 解决的依赖关系
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				//返回null,表示找不到最佳候选Bean对象
				result = null;
			}
			//如果result不是type的实例
			if (!ClassUtils.isAssignableValue(type, result)) {
    
    
				//抛出Bean不是必需类型异常
				throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
			}
			//返回最佳候选Bean对象【result】
			return result;
		}
		finally {
    
    
			//设置上一个切入点对象
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
		}
	}

DefaultListableBeanFactory#resolveMultipleBeans():需要注入的类型是stream,array,collection,map类型的话,解析出来他们的引用类型(如List则会解析出people类型),然后从beanFactory中查找所有是people类型的对象组成相应的集合返回(如,List会查找出所有的people对象组装成List类型返回)

  1. stream类型:调用findAutowireCandidates查找出beanFactory中所有符合类型的bean组装成stream返回;
  2. array类型:调用findAutowireCandidates查找出beanFactory中所有符合类型的bean组装成array返回;
  3. collection类型:调用findAutowireCandidates查找出beanFactory中所有符合类型的bean组装成Collection返回;
  4. Map类型:调用findAutowireCandidates查找出beanFactory中所有符合类型的bean组装成Map返回。
private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) {
    
    

		Class<?> type = descriptor.getDependencyType();
		// stream
		if (descriptor instanceof StreamDependencyDescriptor) {
    
    
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			if (autowiredBeanNames != null) {
    
    
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			Stream<Object> stream = matchingBeans.keySet().stream()
					.map(name -> descriptor.resolveCandidate(name, type, this))
					.filter(bean -> !(bean instanceof NullBean));
			if (((StreamDependencyDescriptor) descriptor).isOrdered()) {
    
    
				stream = stream.sorted(adaptOrderComparator(matchingBeans));
			}
			return stream;
		}
		// 属性是数组类型
		else if (type.isArray()) {
    
    
			Class<?> componentType = type.getComponentType();
			ResolvableType resolvableType = descriptor.getResolvableType();
			Class<?> resolvedArrayType = resolvableType.resolve(type);
			if (resolvedArrayType != type) {
    
    
				componentType = resolvableType.getComponentType().resolve();
			}
			if (componentType == null) {
    
    
				return null;
			}
			// 根据属性类型找到BeanFactory中所有类型的匹配bean
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType,
					new MultiElementDescriptor(descriptor));
			if (matchingBeans.isEmpty()) {
    
    
				return null;
			}
			if (autowiredBeanNames != null) {
    
    
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			// 通过转换器将bean的值转换为对应的type类型
			Object result = converter.convertIfNecessary(matchingBeans.values(), resolvedArrayType);
			if (result instanceof Object[]) {
    
    
				Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
				if (comparator != null) {
    
    
					Arrays.sort((Object[]) result, comparator);
				}
			}
			return result;
		}
		// 属性是Collection类型
		else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
    
    
			Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric();
			if (elementType == null) {
    
    
				return null;
			}
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType,
					new MultiElementDescriptor(descriptor));
			if (matchingBeans.isEmpty()) {
    
    
				return null;
			}
			if (autowiredBeanNames != null) {
    
    
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			Object result = converter.convertIfNecessary(matchingBeans.values(), type);
			if (result instanceof List) {
    
    
				if (((List<?>) result).size() > 1) {
    
    
					Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
					if (comparator != null) {
    
    
						((List<?>) result).sort(comparator);
					}
				}
			}
			return result;
		}
		// 属性是map类型
		else if (Map.class == type) {
    
    
			ResolvableType mapType = descriptor.getResolvableType().asMap();
			Class<?> keyType = mapType.resolveGeneric(0);
			if (String.class != keyType) {
    
    
				return null;
			}
			Class<?> valueType = mapType.resolveGeneric(1);
			if (valueType == null) {
    
    
				return null;
			}
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType,
					new MultiElementDescriptor(descriptor));
			if (matchingBeans.isEmpty()) {
    
    
				return null;
			}
			if (autowiredBeanNames != null) {
    
    
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			return matchingBeans;
		}
		else {
    
    
			return null;
		}
	}

DefaultListableBeanFactory#findAutowireCandidates():从beanFactory中获取所有requiredType类型的对象,组装成< K:beanName,V:beanObject >形式返回。

protected Map<String, Object> findAutowireCandidates(
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
    
    

		// 获取requiredType对应的bean名字数组
		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
				this, requiredType, true, descriptor.isEager());
		Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
		for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
    
    
			Class<?> autowiringType = classObjectEntry.getKey();
			if (autowiringType.isAssignableFrom(requiredType)) {
    
    
				Object autowiringValue = classObjectEntry.getValue();
				autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
				if (requiredType.isInstance(autowiringValue)) {
    
    
					result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
					break;
				}
			}
		}
		// 自定义的相关处理
		for (String candidate : candidateNames) {
    
    
			if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
    
    
				addCandidateEntry(result, candidate, descriptor, requiredType);
			}
		}
		// 空的处理
		if (result.isEmpty()) {
    
    
			boolean multiple = indicatesMultipleBeans(requiredType);
			// Consider fallback matches if the first pass failed to find anything...
			DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
			for (String candidate : candidateNames) {
    
    
				if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
						(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
    
    
					addCandidateEntry(result, candidate, descriptor, requiredType);
				}
			}
			if (result.isEmpty() && !multiple) {
    
    
				// Consider self references as a final pass...
				// but in the case of a dependency collection, not the very same bean itself.
				for (String candidate : candidateNames) {
    
    
					if (isSelfReference(beanName, candidate) &&
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) {
    
    
						addCandidateEntry(result, candidate, descriptor, requiredType);
					}
				}
			}
		}
		return result;
	}

四,@Autowired:通过bean的后置处理器AutowiredAnnotationBeanPostProcessor对@Autowired注解属性填充

Person.java

@Component
public class Person {
    
    
    @Autowired
    private People people;
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.bobo.selfAutowired.annotation"/>
</beans>

AutowiredAnnotationBeanPostProcessor#postProcessProperties():从缓存中取出这个bean对应的依赖注入的元信息InjectionMetadata:其中属性injectedElements记录了当前类需要注入的所有属性:

在这里插入图片描述

	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    
    
		// 从缓存中取出这个bean对应的依赖注入的元信息~
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
		try {
    
    
			// 进行属性注入
			metadata.inject(bean, beanName, pvs);
		}
		catch (BeanCreationException ex) {
    
    
			throw ex;
		}
		catch (Throwable ex) {
    
    
			throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
		}
		return pvs;
	}

InjectionMetadata#inject():遍历需要注入的所有属性elementsToIterate,一个一个属性注入

	public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    
    
		Collection<InjectedElement> checkedElements = this.checkedElements;
		Collection<InjectedElement> elementsToIterate =
				(checkedElements != null ? checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) {
    
    
			for (InjectedElement element : elementsToIterate) {
    
    
				if (logger.isTraceEnabled()) {
    
    
					logger.trace("Processing injected element of bean '" + beanName + "': " + element);
				}
				element.inject(target, beanName, pvs);
			}
		}
	}

AutowiredAnnotationBeanPostProcessor#inject():调用beanFactory.resolveDependency()方法找出所要注入的候选bean然后通过反射给属性赋值,beanFactory.resolveDependency()方法上面已经分析过了,此处省略。

	protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    
    
			Field field = (Field) this.member;
			Object value;
			// 如果缓存,从缓存中获取
			if (this.cached) {
    
    
				// 如果  cachedFieldValue instanceof DependencyDescriptor。则调用 resolveDependency 方法重新加载。
				value = resolvedCachedArgument(beanName, this.cachedFieldValue);
			}
			else {
    
    
				// 否则调用了 resolveDependency 方法。这个在前篇讲过,在 populateBean 方法中按照类型注入的时候就是通过此方法,
				// 也就是说明了 @Autowired 和 @Inject默认是 按照类型注入的
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
				desc.setContainingClass(bean.getClass());
				Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
				Assert.state(beanFactory != null, "No BeanFactory available");
				// 转换器使用的bean工厂的转换器
				TypeConverter typeConverter = beanFactory.getTypeConverter();
				try {
    
    
					// 获取依赖的value值的工作  最终还是委托给beanFactory.resolveDependency()去完成的
					// 这个接口方法由AutowireCapableBeanFactory提供,它提供了从bean工厂里获取依赖值的能力
					value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
				}
				catch (BeansException ex) {
    
    
					throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
				}
				// 把缓存值缓存起来
				synchronized (this) {
    
    
					// 如果没有缓存,则开始缓存
					if (!this.cached) {
    
    
						// 可以看到value!=null并且required=true才会进行缓存的处理
						if (value != null || this.required) {
    
    
							// 这里先缓存一下 desc,如果下面 utowiredBeanNames.size() > 1。则在上面从缓存中获取的时候会重新获取。
							this.cachedFieldValue = desc;
							// 注册依赖bean
							registerDependentBeans(beanName, autowiredBeanNames);
							// autowiredBeanNames里可能会有别名的名称,所以size可能大于1
							if (autowiredBeanNames.size() == 1) {
    
    
								// beanFactory.isTypeMatch挺重要的,因为@Autowired是按照类型注入的
								String autowiredBeanName = autowiredBeanNames.iterator().next();
								if (beanFactory.containsBean(autowiredBeanName) &&
										beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
    
    
									this.cachedFieldValue = new ShortcutDependencyDescriptor(
											desc, autowiredBeanName, field.getType());
								}
							}
						}
						else {
    
    
							this.cachedFieldValue = null;
						}
						this.cached = true;
					}
				}
			}
			if (value != null) {
    
    
				// 通过反射,给属性赋值
				ReflectionUtils.makeAccessible(field);
				field.set(bean, value);
			}
		}
	}

五,applyPropertyValues()给放入pvs中的属性赋值

上面我们分析过,通过autowireByName,autowireByType注入时都会把找到的属性和对象放入到pvs的propertyValueList,所以此处applyPropertyValues()方法是对里面的属性进行赋值操作的:

	protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    
    
		// 为空,直接返回
		if (pvs.isEmpty()) {
    
    
			return;
		}

		// 如果有安全管理器,且bw是BeanWrapperImpl的实例
		if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
    
    
			// 设置bw的安全上下文为工厂的访问控制上下文
			((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
		}

		//MutablePropertyValues:PropertyValues接口的默认实现。允许对属性进行简单操作,并提供构造函数来支持从映射 进行深度复制和构造
		MutablePropertyValues mpvs = null;
		// 原始属性列表
		List<PropertyValue> original;

		// 如果pvs是MutablePropertyValues
		if (pvs instanceof MutablePropertyValues) {
    
    
			// 类型强制转换
			mpvs = (MutablePropertyValues) pvs;
			//isConverted:返回该holder是否只包含转换后的值(true),或者是否仍然需要转换这些值
			//如果mpvs只包含转换后的值
			if (mpvs.isConverted()) {
    
    
				// Shortcut: use the pre-converted values as-is.
				try {
    
    
					// 已完成,直接返回
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
    
    
					//捕捉Bean异常,重新抛出Bean创佳异常:错误设置属性值。
					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();
		// 如果转换器为空,则直接把包装类赋值给converter
		if (converter == null) {
    
    
			converter = bw;
		}
		//BeanDefinitionValueResolver:在bean工厂实现中使用Helper类,它将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中
				deepCopy.add(pv);
			}
			// 如果属性没有被解析过
			else {
    
    
				// 获取属性的名字
				String propertyName = pv.getName();
				// 获取未经类型转换的值
				Object originalValue = pv.getValue();
				//AutowiredPropertyMarker.INSTANCE:自动生成标记的规范实例
				if (originalValue == AutowiredPropertyMarker.INSTANCE) {
    
    
					//获取propertyName在bw中的setter方法
					Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
					//如果setter方法为null
					if (writeMethod == null) {
    
    
						//抛出非法参数异常:自动装配标记属性没有写方法。
						throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
					}
					//将writerMethod封装到DependencyDescriptor对象
					originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
				}
				//交由valueResolver根据pv解析出originalValue所封装的对象
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				//默认转换后的值是刚解析出来的值
				Object convertedValue = resolvedValue;
				//可转换标记: propertyName是否bw中的可写属性 && prepertyName不是表示索引属性或嵌套属性(如果propertyName中有'.'||'['就认为是索引属性或嵌套属性)
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				//如果可转换
				if (convertible) {
    
    
					//将resolvedValue转换为指定的目标属性对象
					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.
				// 可以将转换后的值存储合并后BeanDefinition中,以避免对每个创建的Bean实例进行重新转换
				//如果resolvedValue与originalValue是同一个对象
				if (resolvedValue == originalValue) {
    
    
					//如果可转换
					if (convertible) {
    
    
						//将convertedValue设置到pv中
						pv.setConvertedValue(convertedValue);
					}
					//将pv添加到deepCopy中
					deepCopy.add(pv);
				}
				//TypedStringValue:类型字符串的Holder,这个holder将只存储字符串值和目标类型。实际得转换将由Bean工厂执行
				//如果可转换 && originalValue是TypedStringValue的实例 && orginalValue不是标记为动态【即不是一个表达式】&&
				// 	convertedValue不是Collection对象 或 数组
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).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));
				}
			}
		}
		//mpvs不为null && 已经不需要解析
		if (mpvs != null && !resolveNecessary) {
    
    
			//将此holder标记为只包含转换后的值
			mpvs.setConverted();
		}

		// Set our (possibly massaged) deep copy.
		try {
    
    
			//按原样使用deepCopy构造一个新的MutablePropertyValues对象然后设置到bw中以对bw的属性值更新
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
    
    
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}

猜你喜欢

转载自blog.csdn.net/u013277209/article/details/110235934