5.x primavera trip Fuente veintiuno detallada siete getBean

DefaultListableBeanFactory de dependencias resolver doResolveDependency

Continuar sobre los artículos, si se trata de nuestra propia definición del tipo de parámetros, no hay notas de carga diferida, el mismo será resuelto.
Primer vistazo a BeanFactirysi hay que añadir un acceso directo, por lo general no lo hacen, a menos que la extensión de la subclase hereda y, a continuación, ver si hay maneras de establecer el valor del parámetro de anotación, cualquier acuerdo se establece. De lo contrario, se juzga si una pluralidad beande inyección, tal como un conjunto de tipos de parámetros. Finalmente, el objeto es obtener el tipo de montaje automático findAutowireCandidates, si múltiples encontrar las palabras, la prioridad será para seleccionar y, a continuación, se reunieron para crear el tipo de objeto aquí es crear un getBeanproceso, pero puede ser obtenida directamente, en general, se define con el fin de ver el método principal de la fábrica, ya que se puede utilizar el interno ASMproceso, pero si hay nombres duplicados, que está fuera de servicio, y se puede ver por qué no específica ConfigurationClassParserdel retrieveBeanMethodMetadatamétodo, pero no mucho impacto, de todos modos, se puede montar de forma automática. La creación de bueno y luego determinar el tipo de partido, y finalmente regresaron. Vamos a analizar varios aspectos importantes, sobre todo para entender al otro conocerse a sí mismo en la línea.

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
		//设置注入点,并获得前一个注入点,以便后面可以设置回来
		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {//解析快捷方式,存在就返回,子类BeanFactiry可以扩展,默认null
			Object shortcut = descriptor.resolveShortcut(this);
			if (shortcut != null) {
				return shortcut;
			}

			Class<?> type = descriptor.getDependencyType();
			Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);//获取注解可能的值
			if (value != null) {
				if (value instanceof String) {
					String strVal = resolveEmbeddedValue((String) value);
					BeanDefinition bd = (beanName != null && containsBean(beanName) ?
							getMergedBeanDefinition(beanName) : null);
					value = evaluateBeanDefinitionString(strVal, bd);
				}
				TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
				try {
					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()));
				}
			}
			//是否是多个bean的注入,比如参数类型是集合,map
			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
			if (multipleBeans != null) {
				return multipleBeans;
			}
			//寻找装配候选对象
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			if (matchingBeans.isEmpty()) {
				if (isRequired(descriptor)) {//空的话,又是必须的,才会报异常
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				return null;
			}

			String autowiredBeanName;//自动装配的bean名字
			Object instanceCandidate;//装配实例

			if (matchingBeans.size() > 1) {//有多个
				autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
				if (autowiredBeanName == null) {
					if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
						return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
					}
					else {

						return null;
					}
				}
				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();
			}

			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(autowiredBeanName);
			}
			if (instanceCandidate instanceof Class) {//获取装配实例,也要进行getBean过程
				instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
			}
			Object result = instanceCandidate;
			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);
		}
	}

Buscando montaje automático DefaultListableBeanFactory de los findAutowireCandidates Tipo

Aquí vamos a buscar si existe dentro de un parámetros de tipo contenedor, primer tipo de parámetros de beantodas las definiciones de beannombre a saber, para crear una LinkedHashMapcolección, y luego determinar el tipo no es el tipo de interior, que es el caso, debe añadirse a la lista. Entonces atraviesan el conjunto de candidatos de nombres, los otros no autónomos referencia pueden ser añadidos como un tipo dependiente a la colección, si el conjunto está vacío, sino también el procesamiento de determinación, tal no es el tipo de matriz, tipo de conjunto, hacen consecuencia.

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;
	}

addCandidateEntry añade al conjunto candidato en

Si es más que un conjunto de elementos y StreamDependencyDescriptortipos será apropiado para crear bean, y luego en, o escribir directamente en la habitación.

private void addCandidateEntry(Map<String, Object> candidates, String candidateName,
			DependencyDescriptor descriptor, Class<?> requiredType) {

		if (descriptor instanceof MultiElementDescriptor) {
			Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
			if (!(beanInstance instanceof NullBean)) {
				candidates.put(candidateName, beanInstance);
			}
		}
		else if (containsSingleton(candidateName) || (descriptor instanceof StreamDependencyDescriptor &&
				((StreamDependencyDescriptor) descriptor).isOrdered())) {
			Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
			candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance));
		}
		else {
			candidates.put(candidateName, getType(candidateName));
		}
	}

DependencyDescriptor 的 resolveCandidate

Cuando omita el tipo de tiempo de montaje, puede empezar a conseguir realmente ese tipo de objeto, de hecho, dentro y llamar getBeanal.

	public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
			throws BeansException {

		return beanFactory.getBean(beanName);
	}

Proceso general para analizar aquí, no un montón de detalles en profundidad, es más complejo, o la primera cifra a cabo aproximadamente en ponderar mejor los detalles. A continuación tenemos el diagrama de flujo básico bajo total.

Pues bien, hoy aquí, esperamos estudio ayuda y entender, no rocíe el Gran Dios ver, comprender solamente su propio aprendizaje, capacidad limitada, por favor excusa.

Publicados 235 artículos originales · ganado elogios 74 · Vistas a 30000 +

Supongo que te gusta

Origin blog.csdn.net/wangwei19871103/article/details/105093344
Recomendado
Clasificación