⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 constructorresolver.java

📁 spring api 源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
				Class[] paramTypes = candidate.getParameterTypes();

				if (Modifier.isStatic(candidate.getModifiers()) == isStatic &&
						candidate.getName().equals(mbd.getFactoryMethodName()) &&
						paramTypes.length >= minNrOfArgs) {

					ArgumentsHolder args = null;

					if (resolvedValues != null) {
						// Resolved contructor arguments: type conversion and/or autowiring necessary.
						try {
							args = createArgumentArray(
									beanName, mbd, resolvedValues, bw, paramTypes, candidate, autowiring);
						}
						catch (UnsatisfiedDependencyException ex) {
							if (this.beanFactory.logger.isTraceEnabled()) {
								this.beanFactory.logger.trace("Ignoring factory method [" + candidate +
										"] of bean '" + beanName + "': " + ex);
							}
							if (i == candidates.length - 1 && factoryMethodToUse == null) {
								throw ex;
							}
							else {
								// Swallow and try next overloaded factory method.
								continue;
							}
						}
					}

					else {
						// Explicit arguments given -> arguments length must match exactly.
						if (paramTypes.length != explicitArgs.length) {
							continue;
						}
						args = new ArgumentsHolder(explicitArgs);
					}

					int typeDiffWeight = args.getTypeDifferenceWeight(paramTypes);
					// Choose this constructor if it represents the closest match.
					if (typeDiffWeight < minTypeDiffWeight) {
						factoryMethodToUse = candidate;
						argsToUse = args.arguments;
						minTypeDiffWeight = typeDiffWeight;
					}
				}
			}

			if (factoryMethodToUse == null) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName,
						"No matching factory method found: " +
						(mbd.getFactoryBeanName() != null ?
						 "factory bean '" + mbd.getFactoryBeanName() + "'; " : "") +
						"factory method '" + mbd.getFactoryMethodName() + "'");
			}
			mbd.resolvedConstructorOrFactoryMethod = factoryMethodToUse;
		}

		Object beanInstance = this.instantiationStrategy.instantiate(
				mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
		if (beanInstance == null) {
			return null;
		}

		bw.setWrappedInstance(beanInstance);
		return bw;
	}

	/**
	 * Resolve the constructor arguments for this bean into the resolvedValues object.
	 * This may involve looking up other beans.
	 * This method is also used for handling invocations of static factory methods.
	 */
	private int resolveConstructorArguments(
			String beanName, RootBeanDefinition mbd, BeanWrapper bw,
			ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {

		BeanDefinitionValueResolver valueResolver =
				new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, bw);

		int minNrOfArgs = cargs.getArgumentCount();

		for (Iterator it = cargs.getIndexedArgumentValues().entrySet().iterator(); it.hasNext();) {
			Map.Entry entry = (Map.Entry) it.next();
			int index = ((Integer) entry.getKey()).intValue();
			if (index < 0) {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName,
						"Invalid constructor argument index: " + index);
			}
			if (index > minNrOfArgs) {
				minNrOfArgs = index + 1;
			}
			ConstructorArgumentValues.ValueHolder valueHolder =
					(ConstructorArgumentValues.ValueHolder) entry.getValue();
			if (valueHolder.isConverted()) {
				resolvedValues.addIndexedArgumentValue(index, valueHolder);
			}
			else {
				String argName = "constructor argument with index " + index;
				Object resolvedValue = valueResolver.resolveValueIfNecessary(argName, valueHolder.getValue());
				ConstructorArgumentValues.ValueHolder resolvedValueHolder =
						new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType());
				resolvedValueHolder.setSource(valueHolder);
				resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder);
			}
		}

		for (Iterator it = cargs.getGenericArgumentValues().iterator(); it.hasNext();) {
			ConstructorArgumentValues.ValueHolder valueHolder =
					(ConstructorArgumentValues.ValueHolder) it.next();
			if (valueHolder.isConverted()) {
				resolvedValues.addGenericArgumentValue(valueHolder);
			}
			else {
				String argName = "constructor argument";
				Object resolvedValue = valueResolver.resolveValueIfNecessary(argName, valueHolder.getValue());
				ConstructorArgumentValues.ValueHolder resolvedValueHolder =
						new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType());
				resolvedValueHolder.setSource(valueHolder);
				resolvedValues.addGenericArgumentValue(resolvedValueHolder);
			}
		}

		return minNrOfArgs;
	}

	/**
	 * Create an array of arguments to invoke a constructor or factory method,
	 * given the resolved constructor argument values.
	 */
	private ArgumentsHolder createArgumentArray(
			String beanName, RootBeanDefinition mbd, ConstructorArgumentValues resolvedValues,
			BeanWrapper bw, Class[] paramTypes, Object methodOrCtor, boolean autowiring)
			throws UnsatisfiedDependencyException {

		String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method");

		ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
		Set usedValueHolders = new HashSet(paramTypes.length);
		boolean resolveNecessary = false;

		for (int index = 0; index < paramTypes.length; index++) {
			// Try to find matching constructor argument value, either indexed or generic.
			ConstructorArgumentValues.ValueHolder valueHolder =
					resolvedValues.getArgumentValue(index, paramTypes[index], usedValueHolders);
			// If we couldn't find a direct match and are not supposed to autowire,
			// let's try the next generic, untyped argument value as fallback:
			// it could match after type conversion (for example, String -> int).
			if (valueHolder == null && !autowiring) {
				valueHolder = resolvedValues.getGenericArgumentValue(null, usedValueHolders);
			}
			if (valueHolder != null) {
				// We found a potential match - let's give it a try.
				// Do not consider the same value definition multiple times!
				usedValueHolders.add(valueHolder);
				args.rawArguments[index] = valueHolder.getValue();
				if (valueHolder.isConverted()) {
					Object convertedValue = valueHolder.getConvertedValue();
					args.arguments[index] = convertedValue;
					args.preparedArguments[index] = convertedValue;
				}
				else {
					try {
						Object originalValue = valueHolder.getValue();
						Object convertedValue = bw.convertIfNecessary(originalValue, paramTypes[index],
								MethodParameter.forMethodOrConstructor(methodOrCtor, index));
						args.arguments[index] = convertedValue;
						ConstructorArgumentValues.ValueHolder sourceHolder =
								(ConstructorArgumentValues.ValueHolder) valueHolder.getSource();
						Object sourceValue = sourceHolder.getValue();
						if (originalValue == sourceValue || sourceValue instanceof TypedStringValue) {
							// Either a converted value or still the original one: store converted value.
							sourceHolder.setConvertedValue(convertedValue);
							args.preparedArguments[index] = convertedValue;
						}
						else {
							resolveNecessary = true;
							args.preparedArguments[index] = sourceValue;
						}
					}
					catch (TypeMismatchException ex) {
						throw new UnsatisfiedDependencyException(
								mbd.getResourceDescription(), beanName, index, paramTypes[index],
								"Could not convert " + methodType + " argument value of type [" +
								ObjectUtils.nullSafeClassName(valueHolder.getValue()) +
								"] to required type [" + paramTypes[index].getName() + "]: " + ex.getMessage());
					}
				}
			}
			else {
				// No explicit match found: we're either supposed to autowire or
				// have to fail creating an argument array for the given constructor.
				if (!autowiring) {
					throw new UnsatisfiedDependencyException(
							mbd.getResourceDescription(), beanName, index, paramTypes[index],
							"Ambiguous " + methodType + " argument types - " +
							"did you specify the correct bean references as " + methodType + " arguments?");
				}
				Map matchingBeans = findAutowireCandidates(beanName, paramTypes[index]);
				if (matchingBeans.size() != 1) {
					throw new UnsatisfiedDependencyException(
							mbd.getResourceDescription(), beanName, index, paramTypes[index],
							"There are " + matchingBeans.size() + " beans of type [" + paramTypes[index].getName() +
							"] available for autowiring: " + matchingBeans.keySet() +
							". There should have been exactly 1 to be able to autowire " +
							methodType + " of bean '" + beanName + "'.");
				}
				Map.Entry entry = (Map.Entry) matchingBeans.entrySet().iterator().next();
				String autowiredBeanName = (String) entry.getKey();
				Object autowiredBean = entry.getValue();
				args.rawArguments[index] = autowiredBean;
				args.arguments[index] = autowiredBean;
				args.preparedArguments[index] = new RuntimeBeanReference(autowiredBeanName);
				resolveNecessary = true;
				if (mbd.isSingleton()) {
					this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
				}
				if (this.beanFactory.logger.isDebugEnabled()) {
					this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName +
							"' via " + methodType + " to bean named '" + autowiredBeanName + "'");
				}
			}
		}

		if (resolveNecessary) {
			mbd.preparedConstructorArguments = args.preparedArguments;
		}
		else {
			mbd.resolvedConstructorArguments = args.arguments;
		}
		return args;
	}


	/**
	 * Find bean instances that match the required type.
	 * Called during autowiring for the specified bean.
	 * <p>If a subclass cannot obtain information about bean names by type,
	 * a corresponding exception should be thrown.
	 * @param beanName the name of the bean that is about to be wired
	 * @param requiredType the type of the autowired constructor argument
	 * @return a Map of candidate names and candidate instances that match
	 * the required type (never <code>null</code>)
	 * @throws BeansException in case of errors
	 * @see #autowireConstructor
	 */
	protected abstract Map findAutowireCandidates(String beanName, Class requiredType) throws BeansException;


	/**
	 * Private inner class for holding argument combinations.
	 */
	private static class ArgumentsHolder {

		public Object rawArguments[];

		public Object arguments[];

		public Object preparedArguments[];

		public ArgumentsHolder(int size) {
			this.rawArguments = new Object[size];
			this.arguments = new Object[size];
			this.preparedArguments = new Object[size];
		}

		public ArgumentsHolder(Object[] args) {
			this.rawArguments = args;
			this.arguments = args;
			this.preparedArguments = args;
		}

		public int getTypeDifferenceWeight(Class[] paramTypes) {
			// If valid arguments found, determine type difference weight.
			// Try type difference weight on both the converted arguments and
			// the raw arguments. If the raw weight is better, use it.
			// Decrease raw weight by 1024 to prefer it over equal converted weight.
			int typeDiffWeight = AutowireUtils.getTypeDifferenceWeight(paramTypes, this.arguments);
			int rawTypeDiffWeight = AutowireUtils.getTypeDifferenceWeight(paramTypes, this.rawArguments) - 1024;
			return (rawTypeDiffWeight < typeDiffWeight ? rawTypeDiffWeight : typeDiffWeight);
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -