【Spring源代码阅读之十一】populateBean()方法对@Autowired和@Value注解的处理

populateBean方法对@Autowired和@Value注解的处理相关代码阅读

  • 导图(关注黄色populateBean方法第4步)
  • populateBean方法的处理逻辑
  • AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues
        • findAutowiringMetadata
        • buildAutowiringMetadata
        • findAutowiredAnnotation
    • InjectionMetadata#inject
        • AutowiredFieldElement#inject
        • AutowiredMethodElement#inject
            • DefaultListableBeanFactory#resolveDependency
            • doResolveDependency
            • resolveMultipleBeans

导图(关注黄色populateBean方法第4步)

【Spring源代码阅读之十一】populateBean()方法对@Autowired和@Value注解的处理_第1张图片

populateBean方法的处理逻辑

/**
 * 遍历InstantiationAwareBeanPostProcessor,可对属性做修改
 * 主要起作用的是CommonAnnotationBeanPostProcessor和AutowiredAnnotationBeanPostProcessor这两个类
 * 解析了{@link Resource} 和 {@link org.springframework.beans.factory.annotation.Autowired}注解
 */
if (hasInstAwareBpps) {
	for (BeanPostProcessor bp : getBeanPostProcessors()) {
		if (bp instanceof InstantiationAwareBeanPostProcessor) {
			InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
			pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
			if (pvs == null) {
				return;
			}
		}
	}
}

AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues

/**
 * 解析需要注入的属性和方法
 */
@Override
public PropertyValues postProcessPropertyValues(
		PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {

	/**
	 * 获取需要注入的元信息
	 */
	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;
}

findAutowiringMetadata

/**
 * 寻找需要注入的属性元信息
 */
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
	// Fall back to class name as cache key, for backwards compatibility with custom callers.
	/**
	 * 生成缓存的key
	 */
	String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
	// Quick check on the concurrent map first, with minimal locking.
	/**
	 * 查看缓存中有没有
	 */
	InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
	/**
	 * 缓存中没有或者缓存中的Class与现在的Class不一样,则进行分析查找自动注入的属性
	 * if代码块中用到了双重检查
	 */
	if (InjectionMetadata.needsRefresh(metadata, clazz)) {
		synchronized (this.injectionMetadataCache) {
			metadata = this.injectionMetadataCache.get(cacheKey);
			if (InjectionMetadata.needsRefresh(metadata, clazz)) {
				/**
				 * 缓存中存在但是Class已经不一致了,则将pvs中封装的参数清除
				 */
				if (metadata != null) {
					metadata.clear(pvs);
				}
				/**
				 * 解析需要注入的属性元信息,并缓存起来
				 */
				metadata = buildAutowiringMetadata(clazz);
				this.injectionMetadataCache.put(cacheKey, metadata);
			}
		}
	}
	return metadata;
}

buildAutowiringMetadata

/**
 * 构建需要注入属性的元信息
 */
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
	List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
	Class<?> targetClass = clazz;

	do {
		final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

		/**
		 * 首先查找需要注入的属性
		 */
		ReflectionUtils.doWithLocalFields(targetClass, field -> {
			/**
			 * 查找属性上的注入注解
			 */
			AnnotationAttributes ann = findAutowiredAnnotation(field);
			if (ann != null) {
				/**
				 * 如果属性是static修饰的,则不对其进行自动注入
				 */
				if (Modifier.isStatic(field.getModifiers())) {
					if (logger.isWarnEnabled()) {
						logger.warn("Autowired annotation is not supported on static fields: " + field);
					}
					return;
				}
				/**
				 * 解析@Autowired中的required属性,为true的话注入失败会报错,为false的话允许失败
				 */
				boolean required = determineRequiredStatus(ann);
				currElements.add(new AutowiredFieldElement(field, required));
			}
		});

		ReflectionUtils.doWithLocalMethods(targetClass, method -> {
			/**
			 * 这里判断是不是桥接方法,是的话就不对其进行解析
			 * 桥接方法的作用是泛型擦除,为了JDK1.5出现的泛型能够兼容1.5之前的代码,所以JDK借助桥接方法实现泛型的擦除
			 * 详细的这里不解释,可以自行百度
			 */
			Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
			if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
				return;
			}
			/**
			 * 以下代码和查找属性代码差不多,这里不再解释
			 */
			AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
			if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
				if (Modifier.isStatic(method.getModifiers())) {
					if (logger.isWarnEnabled()) {
						logger.warn("Autowired annotation is not supported on static methods: " + method);
					}
					return;
				}
				if (method.getParameterCount() == 0) {
					if (logger.isWarnEnabled()) {
						logger.warn("Autowired annotation should only be used on methods with parameters: " +
								method);
					}
				}
				boolean required = determineRequiredStatus(ann);
				PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
				currElements.add(new AutowiredMethodElement(method, required, pd));
			}
		});

		elements.addAll(0, currElements);
		/**
		 * 这里遍历了父类,所以整个的分析代码是在一个大的while循环中的
		 */
		targetClass = targetClass.getSuperclass();
	}
	while (targetClass != null && targetClass != Object.class);

	return new InjectionMetadata(clazz, elements);
}

findAutowiredAnnotation

/**
 * 构造方法中添加需要解析的注入注解
 */
@SuppressWarnings("unchecked")
public AutowiredAnnotationBeanPostProcessor() {
	/**
	 * 注入需要解析的注解
	 */
	this.autowiredAnnotationTypes.add(Autowired.class);
	this.autowiredAnnotationTypes.add(Value.class);
	try {
		this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
				ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
		logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
	}
	catch (ClassNotFoundException ex) {
		// JSR-330 API not available - simply skip.
	}
}
/**
 * 查找注入的注解,包括@Autowired和@Value
 * 这两个注解在默认构造方法中添加到集合中的
 */
@Nullable
private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
	if (ao.getAnnotations().length > 0) {  // autowiring annotations have to be local
		for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
			AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
			if (attributes != null) {
				return attributes;
			}
		}
	}
	return null;
}

InjectionMetadata#inject

/**
 * 遍历其中需要解析的属性或方法,进行解析
 */
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.isDebugEnabled()) {
				logger.debug("Processing injected element of bean '" + beanName + "': " + element);
			}
			/**
			 * 解析属性上的注入注解
			 * @see AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject(java.lang.Object, java.lang.String, org.springframework.beans.PropertyValues)
			 * 解析方法上的注入注解
			 * @see AutowiredAnnotationBeanPostProcessor.AutowiredMethodElement#inject(java.lang.Object, java.lang.String, org.springframework.beans.PropertyValues)
			 */
			element.inject(target, beanName, pvs);
		}
	}
}

AutowiredFieldElement#inject

/**
 * 解析需要注入的属性
 */
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
	Field field = (Field) this.member;
	Object value;
	/**
	 * 判断有没有缓存过,有缓存过则直接从缓存中解析获取
	 */
	if (this.cached) {
		value = resolvedCachedArgument(beanName, this.cachedFieldValue);
	}
	else {
		/**
		 * 构建依赖关系描述符,利用工厂方法进行解析
		 */
		DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
		desc.setContainingClass(bean.getClass());
		Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
		Assert.state(beanFactory != null, "No BeanFactory available");
		TypeConverter typeConverter = beanFactory.getTypeConverter();
		try {
			/**
			 * 使用工厂的依赖关系解析方法对其进行解析
			 * @see DefaultListableBeanFactory#resolveDependency(org.springframework.beans.factory.config.DependencyDescriptor, java.lang.String, java.util.Set, org.springframework.beans.TypeConverter)
			 */
			value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
		}
		catch (BeansException ex) {
			throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
		}
		/**
		 * 最终目的是进行缓存
		 */
		synchronized (this) {
			if (!this.cached) {
				if (value != null || this.required) {
					this.cachedFieldValue = desc;
					registerDependentBeans(beanName, autowiredBeanNames);
					if (autowiredBeanNames.size() == 1) {
						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;
			}
		}
	}
	/**
	 * 解析出了依赖,则利用反射直接将值设置进Bean实例中
	 */
	if (value != null) {
		ReflectionUtils.makeAccessible(field);
		field.set(bean, value);
	}
}
}

AutowiredMethodElement#inject

/**
 * 解析需要注入的方法,和属性思路差不过(可参阅属性的注入)
 * 只不过方法中会有多个参数,需要遍历这些参数解析,然后利用反射执行这个方法
 */
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
	if (checkPropertySkipping(pvs)) {
		return;
	}
	Method method = (Method) this.member;
	Object[] arguments;
	if (this.cached) {
		// Shortcut for avoiding synchronization...
		arguments = resolveCachedArguments(beanName);
	}
	else {
		Class<?>[] paramTypes = method.getParameterTypes();
		arguments = new Object[paramTypes.length];
		DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length];
		Set<String> autowiredBeans = new LinkedHashSet<>(paramTypes.length);
		Assert.state(beanFactory != null, "No BeanFactory available");
		TypeConverter typeConverter = beanFactory.getTypeConverter();
		for (int i = 0; i < arguments.length; i++) {
			MethodParameter methodParam = new MethodParameter(method, i);
			DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
			currDesc.setContainingClass(bean.getClass());
			descriptors[i] = currDesc;
			try {
				/**
				 * @see DefaultListableBeanFactory#resolveDependency(org.springframework.beans.factory.config.DependencyDescriptor, java.lang.String, java.util.Set, org.springframework.beans.TypeConverter)
				 */
				Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
				if (arg == null && !this.required) {
					arguments = null;
					break;
				}
				arguments[i] = arg;
			}
			catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);
			}
		}
		/**
		 * 进行缓存
		 */
		synchronized (this) {
			if (!this.cached) {
				if (arguments != null) {
					Object[] cachedMethodArguments = new Object[paramTypes.length];
					System.arraycopy(descriptors, 0, cachedMethodArguments, 0, arguments.length);
					registerDependentBeans(beanName, autowiredBeans);
					if (autowiredBeans.size() == paramTypes.length) {
						Iterator<String> it = autowiredBeans.iterator();
						for (int i = 0; i < paramTypes.length; i++) {
							String autowiredBeanName = it.next();
							if (beanFactory.containsBean(autowiredBeanName) &&
									beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
								cachedMethodArguments[i] = new ShortcutDependencyDescriptor(
										descriptors[i], autowiredBeanName, paramTypes[i]);
							}
						}
					}
					this.cachedMethodArguments = cachedMethodArguments;
				}
				else {
					this.cachedMethodArguments = null;
				}
				this.cached = true;
			}
		}
	}
	/**
	 * 执行方法
	 */
	if (arguments != null) {
		try {
			ReflectionUtils.makeAccessible(method);
			method.invoke(bean, arguments);
		}
		catch (InvocationTargetException ex) {
			throw ex.getTargetException();
		}
	}
}
DefaultListableBeanFactory#resolveDependency
/**
 * 根据此工厂中定义的bean解析指定的依赖关系
 */
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	/**
	 * 设置方法参数名的解析器策略
	 */
	descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
	/**
	 * 获取方法参数的包装类型或字段的声明类型是否是Optional类型
	 * 此类型是包装类,可优雅判断空情况
	 * 则返回包装有实际Bean的Optional对象
	 */
	if (Optional.class == descriptor.getDependencyType()) {
		return createOptionalDependency(descriptor, requestingBeanName);
	}
	/**
	 * ObjectProvider和javax.inject.Provider与ObjectFactory意义差不多,只不过是不同的机构定义的标准
	 * ObjectProvider是ObjectFactory的一种变体,没用过
	 */
	else if (ObjectFactory.class == descriptor.getDependencyType() ||
			ObjectProvider.class == descriptor.getDependencyType()) {
		return new DependencyObjectProvider(descriptor, requestingBeanName);
	}
	else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
		return new Jsr330ProviderFactory().createDependencyProvider(descriptor, requestingBeanName);
	}
	else {
		/**
		 * 解析需要注入的setter方法或属性上是否有Lazy注解
		 * 1、存在的话就返回一个代理对象使其依赖上,并不是真正的Bean,当调用的时候再从容器中获取真正的Bean
		 * 		这样可以在解析依赖的时候不触发依赖Bean的创建,但是本Bean中的属性就一直为代理Bean了,
		 * 		无论是第一次还是多次调用时,真正的Bean不会替换这个代理Bean
		 * 2、不存在的话就返回空,从容器中获取真正的Bean使其依赖上
		 * @see org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver#getLazyResolutionProxyIfNecessary(org.springframework.beans.factory.config.DependencyDescriptor, java.lang.String)
		 */
		Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
				descriptor, requestingBeanName);
		/**
		 * 直接进行依赖,利用依赖项描述符从容器中获取
		 */
		if (result == null) {
			result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
		}
		return result;
	}
}
doResolveDependency
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	/**
	 * 将依赖项描述符设置进本地线程中
	 */
	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		/**
		 * 利用快捷缓存解析获取此依赖项,Spring默认返回空
		 * 意义在于程序员可以在子类工厂中重写此方法进行快捷获取
		 */
		Object shortcut = descriptor.resolveShortcut(this);
		if (shortcut != null) {
			return shortcut;
		}

		/**
		 * 获取setter方法的参数类型或属性的类型
		 */
		Class<?> type = descriptor.getDependencyType();
		/**
		 * 获取Setter方法或属性上{@link org.springframework.beans.factory.annotation.Value}注解中的参数
		 * 里面代码自行断点查看,不解释
		 * @see QualifierAnnotationAutowireCandidateResolver#getSuggestedValue(org.springframework.beans.factory.config.DependencyDescriptor)
		 */
		Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
		/**
		 * 存在@Value注解则需要对其进行解析
		 */
		if (value != null) {
			/**
			 * 注解中的value属性值是String类型的(只能是String类型的)
			 */
			if (value instanceof String) {
				/**
				 * 使用属性值字符串解析器解析,解析@Value("${xxxx}")用法,获取配置文件中的配置
				 */
				String strVal = resolveEmbeddedValue((String) value);
				/**
				 * 获取依赖项所在Bean的BeanDefinition
				 */
				BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
				/**
				 * 解析字符串,可能将其解析为表达式(Spel表达式)
				 * 例如:@Value("#{service.getDict()}"),获取容器中一个实例的方法或属性,
				 * 		这种方式有限制,具体自行百度测试
				 */
				value = evaluateBeanDefinitionString(strVal, bd);
			}
			/**
			 * 获取类型转换器
			 */
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			/**
			 * 查看依赖描述符中是否是属性依赖还是Setter方法依赖,并进入不同的方法中
			 * 以下两个方法最后进入的是同一个方法,只不过通过参数来对那一个方法进行处理
			 * Setter方法依赖
			 * @see TypeConverterSupport#convertIfNecessary(java.lang.Object, java.lang.Class, org.springframework.core.MethodParameter)
			 * 属性依赖
			 * @see TypeConverterSupport#convertIfNecessary(java.lang.Object, java.lang.Class, java.lang.reflect.Field)
			 * 最终都会进入的方法
			 * @see TypeConverterSupport#doConvert(java.lang.Object, java.lang.Class, org.springframework.core.MethodParameter, java.lang.reflect.Field)
			 */
			return (descriptor.getField() != null ?
					converter.convertIfNecessary(value, type, descriptor.getField()) :
					converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
		}

		/**
		 * 解析依赖的类型是数组、集合情况
		 */
		Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
		if (multipleBeans != null) {
			return multipleBeans;
		}

		/**
		 * 获得容器中所有与依赖类型相符的BeanName和Class对象
		 */
		Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
		/**
		 * 如果找不到,判断是否有{@link org.springframework.beans.factory.annotation.Required}注解
		 * 有的话就抛异常,没有则返回空
		 */
		if (matchingBeans.isEmpty()) {
			if (isRequired(descriptor)) {
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			return null;
		}

		/**
		 * 确定注入的BeanName和Class对象
		 */
		String autowiredBeanName;
		Object instanceCandidate;

		/**
		 * 找到依赖的类型在容器中存在多个,则进行处理
		 */
		if (matchingBeans.size() > 1) {
			/**
			 * 获取有没有优先使用的Bean,即查找@Primary和@Priority注解,确定主要使用哪一个
			 */
			autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
			/**
			 * 找不到确定使用的Bean,符合下列条件之一就会抛异常,否则返回空
			 * 		1、依赖项是必须注入的,存在@Required注解
			 * 		2、依赖项不是数组或集合
			 */
			if (autowiredBeanName == null) {
				if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
					return descriptor.resolveNotUnique(type, 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).
					return null;
				}
			}
			/**
			 * 找到确定使用的Bean,则给到变量中
			 */
			instanceCandidate = matchingBeans.get(autowiredBeanName);
		}
		/**
		 * 容器中找到依赖的类型只有一个,则进行赋值
		 */
		else {
			// We have exactly one match.
			Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
			autowiredBeanName = entry.getKey();
			instanceCandidate = entry.getValue();
		}

		/**
		 * 将依赖的BeanName放入到集合中,通过代码追踪可知为了销毁使用
		 */
		if (autowiredBeanNames != null) {
			autowiredBeanNames.add(autowiredBeanName);
		}
		/**
		 * 解析依赖项,从容器中获取实例,实际上就是调用getBean方法
		 */
		if (instanceCandidate instanceof Class) {
			instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
		}
		Object result = instanceCandidate;
		/**
		 * 实例为空(NullBean为Spring内部中对空对象的表示),判断存不存在@Required注解必须注入
		 * 来进行抛异常或返回空
		 */
		if (result instanceof NullBean) {
			if (isRequired(descriptor)) {
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			result = null;
		}
		/**
		 * 判断从容器中找出的实例和依赖的类型是否一致,不一致抛异常
		 */
		if (!ClassUtils.isAssignableValue(type, result)) {
			throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
		}
		return result;
	}
	/**
	 * 将依赖项描述符从本地线程中删除
	 */
	finally {
		ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
	}
}
resolveMultipleBeans
private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) {

	/**
	 * 获取依赖的类型
	 */
	Class<?> type = descriptor.getDependencyType();
	/**
	 * 依赖的类型是数组
	 */
	if (type.isArray()) {
		/**
		 * 获取数组的泛型类型
		 */
		Class<?> componentType = type.getComponentType();
		/**
		 * 获取解析器中能解析的类型
		 */
		ResolvableType resolvableType = descriptor.getResolvableType();
		Class<?> resolvedArrayType = resolvableType.resolve();
		/**
		 * 依赖的类型和解析器中解析的类型不一致时,以解析器中解析类型为主
		 */
		if (resolvedArrayType != null && resolvedArrayType != type) {
			type = resolvedArrayType;
			componentType = resolvableType.getComponentType().resolve();
		}
		/**
		 * 依赖的类型为空,则不解析
		 */
		if (componentType == null) {
			return null;
		}
		/**
		 * 获得容器中所有与依赖类型相符的BeanName为Key,Value为实例(属性未填充)
		 */
		Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType,
				new MultiElementDescriptor(descriptor));
		/**
		 * 容器中不存在则返回空
		 */
		if (matchingBeans.isEmpty()) {
			return null;
		}
		/**
		 * 将依赖的BeanName放入到集合中,通过代码追踪可知为了销毁使用
		 */
		if (autowiredBeanNames != null) {
			autowiredBeanNames.addAll(matchingBeans.keySet());
		}
		/**
		 * 获取类型解析器
		 */
		TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
		/**
		 * 将这些依赖转换成实际的Bean实例返回
		 */
		Object result = converter.convertIfNecessary(matchingBeans.values(), type);
		if (getDependencyComparator() != null && result instanceof Object[]) {
			Arrays.sort((Object[]) result, adaptDependencyComparator(matchingBeans));
		}
		return result;
	}
	/**
	 * 依赖的类型属于单列集合并且是接口,则解析成集合返回,处理思路和数组一样
	 */
	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 (getDependencyComparator() != null && result instanceof List) {
			((List<?>) result).sort(adaptDependencyComparator(matchingBeans));
		}
		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;
	}
}

你可能感兴趣的:(spring源代码)