Java Code Examples for org.springframework.beans.TypeConverter#convertIfNecessary()

The following examples show how to use org.springframework.beans.TypeConverter#convertIfNecessary() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NacosValueAnnotationBeanPostProcessor.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
private Object convertIfNecessary(Method method, Object value) {
	Class<?>[] paramTypes = method.getParameterTypes();
	Object[] arguments = new Object[paramTypes.length];

	TypeConverter converter = beanFactory.getTypeConverter();

	if (arguments.length == 1) {
		return converter.convertIfNecessary(value, paramTypes[0],
				new MethodParameter(method, 0));
	}

	for (int i = 0; i < arguments.length; i++) {
		arguments[i] = converter.convertIfNecessary(value, paramTypes[i],
				new MethodParameter(method, i));
	}

	return arguments;
}
 
Example 2
Source File: PathVariableMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
    String name = ann.name();
    if (name.isEmpty()) {
        name = parameter.getParameterName();
        if (name == null) {
            throw new IllegalArgumentException(
                    "Name for argument type [" + parameter.getNestedParameterType().getName() +
                            "] not available, and parameter name information not found in class file either.");
        }
    }
    Map<String, String> uriTemplateVars = channel.attr(URI_TEMPLATE).get();
    Object arg = (uriTemplateVars != null ? uriTemplateVars.get(name) : null);
    TypeConverter typeConverter = beanFactory.getTypeConverter();
    return typeConverter.convertIfNecessary(arg, parameter.getParameterType());
}
 
Example 3
Source File: ServerEndpointExporter.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
private <T> T resolveAnnotationValue(Object value, Class<T> requiredType, String paramName) {
    if (value == null) {
        return null;
    }
    TypeConverter typeConverter = beanFactory.getTypeConverter();

    if (value instanceof String) {
        String strVal = beanFactory.resolveEmbeddedValue((String) value);
        BeanExpressionResolver beanExpressionResolver = beanFactory.getBeanExpressionResolver();
        if (beanExpressionResolver != null) {
            value = beanExpressionResolver.evaluate(strVal, new BeanExpressionContext(beanFactory, null));
        } else {
            value = strVal;
        }
    }
    try {
        return typeConverter.convertIfNecessary(value, requiredType);
    } catch (TypeMismatchException e) {
        throw new IllegalArgumentException("Failed to convert value of parameter '" + paramName + "' to required type '" + requiredType.getName() + "'");
    }
}
 
Example 4
Source File: ObjectUtils.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
public static Object convertIfNecessary(ConfigurableListableBeanFactory beanFactory,
		Method method, Object value) {
	Class<?>[] paramTypes = method.getParameterTypes();
	Object[] arguments = new Object[paramTypes.length];

	TypeConverter converter = beanFactory.getTypeConverter();

	if (arguments.length == 1) {
		return converter.convertIfNecessary(value, paramTypes[0],
				new MethodParameter(method, 0));
	}

	for (int i = 0; i < arguments.length; i++) {
		arguments[i] = converter.convertIfNecessary(value, paramTypes[i],
				new MethodParameter(method, i));
	}

	return arguments;
}
 
Example 5
Source File: JndiObjectFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Look up the JNDI object and store it.
 */
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
	super.afterPropertiesSet();

	if (this.proxyInterfaces != null || !this.lookupOnStartup || !this.cache || this.exposeAccessContext) {
		// We need to create a proxy for this...
		if (this.defaultObject != null) {
			throw new IllegalArgumentException(
					"'defaultObject' is not supported in combination with 'proxyInterface'");
		}
		// We need a proxy and a JndiObjectTargetSource.
		this.jndiObject = JndiObjectProxyFactory.createJndiObjectProxy(this);
	}
	else {
		if (this.defaultObject != null && getExpectedType() != null &&
				!getExpectedType().isInstance(this.defaultObject)) {
			TypeConverter converter = (this.beanFactory != null ?
					this.beanFactory.getTypeConverter() : new SimpleTypeConverter());
			try {
				this.defaultObject = converter.convertIfNecessary(this.defaultObject, getExpectedType());
			}
			catch (TypeMismatchException ex) {
				throw new IllegalArgumentException("Default object [" + this.defaultObject + "] of type [" +
						this.defaultObject.getClass().getName() + "] is not of expected type [" +
						getExpectedType().getName() + "] and cannot be converted either", ex);
			}
		}
		// Locate specified JNDI object.
		this.jndiObject = lookupWithFallback();
	}
}
 
Example 6
Source File: RequestParamMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    RequestParam ann = parameter.getParameterAnnotation(RequestParam.class);
    String name = ann.name();
    if (name.isEmpty()) {
        name = parameter.getParameterName();
        if (name == null) {
            throw new IllegalArgumentException(
                    "Name for argument type [" + parameter.getNestedParameterType().getName() +
                            "] not available, and parameter name information not found in class file either.");
        }
    }

    if (!channel.hasAttr(REQUEST_PARAM)) {
        QueryStringDecoder decoder = new QueryStringDecoder(((FullHttpRequest) object).uri());
        channel.attr(REQUEST_PARAM).set(decoder.parameters());
    }

    Map<String, List<String>> requestParams = channel.attr(REQUEST_PARAM).get();
    List<String> arg = (requestParams != null ? requestParams.get(name) : null);
    TypeConverter typeConverter = beanFactory.getTypeConverter();
    if (arg == null) {
        if ("\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n".equals(ann.defaultValue())) {
            return null;
        }else {
            return typeConverter.convertIfNecessary(ann.defaultValue(), parameter.getParameterType());
        }
    }
    if (List.class.isAssignableFrom(parameter.getParameterType())) {
        return typeConverter.convertIfNecessary(arg, parameter.getParameterType());
    } else {
        return typeConverter.convertIfNecessary(arg.get(0), parameter.getParameterType());
    }
}
 
Example 7
Source File: EventMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    if (object==null) {
        return null;
    }
    TypeConverter typeConverter = beanFactory.getTypeConverter();
    return typeConverter.convertIfNecessary(object, parameter.getParameterType());
}
 
Example 8
Source File: JndiObjectFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Look up the JNDI object and store it.
 */
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
	super.afterPropertiesSet();

	if (this.proxyInterfaces != null || !this.lookupOnStartup || !this.cache || this.exposeAccessContext) {
		// We need to create a proxy for this...
		if (this.defaultObject != null) {
			throw new IllegalArgumentException(
					"'defaultObject' is not supported in combination with 'proxyInterface'");
		}
		// We need a proxy and a JndiObjectTargetSource.
		this.jndiObject = JndiObjectProxyFactory.createJndiObjectProxy(this);
	}
	else {
		if (this.defaultObject != null && getExpectedType() != null &&
				!getExpectedType().isInstance(this.defaultObject)) {
			TypeConverter converter = (this.beanFactory != null ?
					this.beanFactory.getTypeConverter() : new SimpleTypeConverter());
			try {
				this.defaultObject = converter.convertIfNecessary(this.defaultObject, getExpectedType());
			}
			catch (TypeMismatchException ex) {
				throw new IllegalArgumentException("Default object [" + this.defaultObject + "] of type [" +
						this.defaultObject.getClass().getName() + "] is not of expected type [" +
						getExpectedType().getName() + "] and cannot be converted either", ex);
			}
		}
		// Locate specified JNDI object.
		this.jndiObject = lookupWithFallback();
	}
}
 
Example 9
Source File: ConstructorResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw,
		Executable executable, Object[] argsToResolve, boolean fallback) {

	TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
	TypeConverter converter = (customConverter != null ? customConverter : bw);
	BeanDefinitionValueResolver valueResolver =
			new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
	Class<?>[] paramTypes = executable.getParameterTypes();

	Object[] resolvedArgs = new Object[argsToResolve.length];
	for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
		Object argValue = argsToResolve[argIndex];
		MethodParameter methodParam = MethodParameter.forExecutable(executable, argIndex);
		GenericTypeResolver.resolveParameterType(methodParam, executable.getDeclaringClass());
		if (argValue instanceof AutowiredArgumentMarker) {
			argValue = resolveAutowiredArgument(methodParam, beanName, null, converter, fallback);
		}
		else if (argValue instanceof BeanMetadataElement) {
			argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
		}
		else if (argValue instanceof String) {
			argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
		}
		Class<?> paramType = paramTypes[argIndex];
		try {
			resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
		}
		catch (TypeMismatchException ex) {
			throw new UnsatisfiedDependencyException(
					mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
					"Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(argValue) +
					"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
		}
	}
	return resolvedArgs;
}
 
Example 10
Source File: MapFactoryBean.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Map<Object, Object> createInstance() {
	if (this.sourceMap == null) {
		throw new IllegalArgumentException("'sourceMap' is required");
	}
	Map<Object, Object> result = null;
	if (this.targetMapClass != null) {
		result = BeanUtils.instantiateClass(this.targetMapClass);
	}
	else {
		result = new LinkedHashMap<Object, Object>(this.sourceMap.size());
	}
	Class<?> keyType = null;
	Class<?> valueType = null;
	if (this.targetMapClass != null) {
		keyType = GenericCollectionTypeResolver.getMapKeyType(this.targetMapClass);
		valueType = GenericCollectionTypeResolver.getMapValueType(this.targetMapClass);
	}
	if (keyType != null || valueType != null) {
		TypeConverter converter = getBeanTypeConverter();
		for (Map.Entry<?, ?> entry : this.sourceMap.entrySet()) {
			Object convertedKey = converter.convertIfNecessary(entry.getKey(), keyType);
			Object convertedValue = converter.convertIfNecessary(entry.getValue(), valueType);
			result.put(convertedKey, convertedValue);
		}
	}
	else {
		result.putAll(this.sourceMap);
	}
	return result;
}
 
Example 11
Source File: ConstructorResolver.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
		String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

	Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
			((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());
	TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ?
			this.beanFactory.getCustomTypeConverter() : bw);
	BeanDefinitionValueResolver valueResolver =
			new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
	Object[] resolvedArgs = new Object[argsToResolve.length];
	for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
		Object argValue = argsToResolve[argIndex];
		MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
		GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
		if (argValue instanceof AutowiredArgumentMarker) {
			argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
		}
		else if (argValue instanceof BeanMetadataElement) {
			argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
		}
		else if (argValue instanceof String) {
			argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
		}
		Class<?> paramType = paramTypes[argIndex];
		try {
			resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
		}
		catch (TypeMismatchException ex) {
			String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method");
			throw new UnsatisfiedDependencyException(
					mbd.getResourceDescription(), beanName, argIndex, paramType,
					"Could not convert " + methodType + " argument value of type [" +
					ObjectUtils.nullSafeClassName(argValue) +
					"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
		}
	}
	return resolvedArgs;
}
 
Example 12
Source File: MapFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Map<Object, Object> createInstance() {
	if (this.sourceMap == null) {
		throw new IllegalArgumentException("'sourceMap' is required");
	}
	Map<Object, Object> result = null;
	if (this.targetMapClass != null) {
		result = BeanUtils.instantiateClass(this.targetMapClass);
	}
	else {
		result = new LinkedHashMap<Object, Object>(this.sourceMap.size());
	}
	Class<?> keyType = null;
	Class<?> valueType = null;
	if (this.targetMapClass != null) {
		ResolvableType mapType = ResolvableType.forClass(this.targetMapClass).asMap();
		keyType = mapType.resolveGeneric(0);
		valueType = mapType.resolveGeneric(1);
	}
	if (keyType != null || valueType != null) {
		TypeConverter converter = getBeanTypeConverter();
		for (Map.Entry<?, ?> entry : this.sourceMap.entrySet()) {
			Object convertedKey = converter.convertIfNecessary(entry.getKey(), keyType);
			Object convertedValue = converter.convertIfNecessary(entry.getValue(), valueType);
			result.put(convertedKey, convertedValue);
		}
	}
	else {
		result.putAll(this.sourceMap);
	}
	return result;
}
 
Example 13
Source File: ConstructorResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw,
		Executable executable, Object[] argsToResolve, boolean fallback) {

	TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
	TypeConverter converter = (customConverter != null ? customConverter : bw);
	BeanDefinitionValueResolver valueResolver =
			new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
	Class<?>[] paramTypes = executable.getParameterTypes();

	Object[] resolvedArgs = new Object[argsToResolve.length];
	for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
		Object argValue = argsToResolve[argIndex];
		MethodParameter methodParam = MethodParameter.forExecutable(executable, argIndex);
		GenericTypeResolver.resolveParameterType(methodParam, executable.getDeclaringClass());
		if (argValue instanceof AutowiredArgumentMarker) {
			argValue = resolveAutowiredArgument(methodParam, beanName, null, converter, fallback);
		}
		else if (argValue instanceof BeanMetadataElement) {
			argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
		}
		else if (argValue instanceof String) {
			argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
		}
		Class<?> paramType = paramTypes[argIndex];
		try {
			resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
		}
		catch (TypeMismatchException ex) {
			throw new UnsatisfiedDependencyException(
					mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
					"Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(argValue) +
					"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
		}
	}
	return resolvedArgs;
}
 
Example 14
Source File: QualifierAnnotationAutowireCandidateResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on qualified element, if any
		Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
		// Then, check annotation on factory method, if applicable
		if (targetAnnotation == null) {
			targetAnnotation = getFactoryMethodAnnotation(bd, type);
		}
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				try {
					Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
					if (beanType != null) {
						targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Not the usual case - simply forget about the type check...
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}
 
Example 15
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		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()));
			}
		}

		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;
		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 {
					// 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;
				}
			}
			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) {
			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);
	}
}
 
Example 16
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
		Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		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());
			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;
		}

		Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
		if (matchingBeans.isEmpty()) {
			if (isRequired(descriptor)) {
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			return null;
		}

		String autowiredBeanName;
		Object instanceCandidate;

		if (matchingBeans.size() > 1) {
			autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
			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;
				}
			}
			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);
		}
		return (instanceCandidate instanceof Class ?
				descriptor.resolveCandidate(autowiredBeanName, type, this) : instanceCandidate);
	}
	finally {
		ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
	}
}
 
Example 17
Source File: QualifierAnnotationAutowireCandidateResolver.java    From blog_demos with Apache License 2.0 4 votes vote down vote up
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on factory method, if applicable
		Annotation targetAnnotation = getFactoryMethodAnnotation(bd, type);
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
				if (beanType != null) {
					targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}
 
Example 18
Source File: ObjectUtils.java    From nacos-spring-project with Apache License 2.0 4 votes vote down vote up
public static Object convertIfNecessary(ConfigurableListableBeanFactory beanFactory,
		Field field, Object value) {
	TypeConverter converter = beanFactory.getTypeConverter();
	return converter.convertIfNecessary(value, field.getType(), field);
}
 
Example 19
Source File: NacosValueAnnotationBeanPostProcessor.java    From nacos-spring-project with Apache License 2.0 4 votes vote down vote up
private Object convertIfNecessary(Field field, Object value) {
	TypeConverter converter = beanFactory.getTypeConverter();
	return converter.convertIfNecessary(value, field.getType(), field);
}
 
Example 20
Source File: QualifierAnnotationAutowireCandidateResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on qualified element, if any
		Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
		// Then, check annotation on factory method, if applicable
		if (targetAnnotation == null) {
			targetAnnotation = getFactoryMethodAnnotation(bd, type);
		}
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				try {
					Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
					if (beanType != null) {
						targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Not the usual case - simply forget about the type check...
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}