Java Code Examples for org.springframework.util.ClassUtils#isAssignableValue()

The following examples show how to use org.springframework.util.ClassUtils#isAssignableValue() . 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: ConstructorArgumentValues.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Look for the next generic argument value that matches the given type,
 * ignoring argument values that have already been used in the current
 * resolution process.
 * @param requiredType the type to match (can be {@code null} to find
 * an arbitrary next generic argument value)
 * @param requiredName the name to match (can be {@code null} to not
 * match argument values by name, or empty String to match any name)
 * @param usedValueHolders a Set of ValueHolder objects that have already been used
 * in the current resolution process and should therefore not be returned again
 * @return the ValueHolder for the argument, or {@code null} if none found
 */
public ValueHolder getGenericArgumentValue(Class<?> requiredType, String requiredName, Set<ValueHolder> usedValueHolders) {
	for (ValueHolder valueHolder : this.genericArgumentValues) {
		if (usedValueHolders != null && usedValueHolders.contains(valueHolder)) {
			continue;
		}
		if (valueHolder.getName() != null && !"".equals(requiredName) &&
				(requiredName == null || !valueHolder.getName().equals(requiredName))) {
			continue;
		}
		if (valueHolder.getType() != null &&
				(requiredType == null || !ClassUtils.matchesTypeName(requiredType, valueHolder.getType()))) {
			continue;
		}
		if (requiredType != null && valueHolder.getType() == null && valueHolder.getName() == null &&
				!ClassUtils.isAssignableValue(requiredType, valueHolder.getValue())) {
			continue;
		}
		return valueHolder;
	}
	return null;
}
 
Example 2
Source File: ExpressionUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Determines if there is a type converter available in the specified context and
 * attempts to use it to convert the supplied value to the specified type. Throws an
 * exception if conversion is not possible.
 * @param context the evaluation context that may define a type converter
 * @param typedValue the value to convert and a type descriptor describing it
 * @param targetType the type to attempt conversion to
 * @return the converted value
 * @throws EvaluationException if there is a problem during conversion or conversion
 * of the value to the specified type is not supported
 */
@SuppressWarnings("unchecked")
public static <T> T convertTypedValue(EvaluationContext context, TypedValue typedValue, Class<T> targetType) {
	Object value = typedValue.getValue();
	if (targetType == null) {
		return (T) value;
	}
	if (context != null) {
		return (T) context.getTypeConverter().convertValue(
				value, typedValue.getTypeDescriptor(), TypeDescriptor.valueOf(targetType));
	}
	if (ClassUtils.isAssignableValue(targetType, value)) {
		return (T) value;
	}
	throw new EvaluationException("Cannot convert value '" + value + "' to type '" + targetType.getName() + "'");
}
 
Example 3
Source File: GenericMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object fromMessage(Message<?> message, Class<?> targetClass) {
	Object payload = message.getPayload();
	if (targetClass == null) {
		return payload;
	}
	if (payload != null && this.conversionService.canConvert(payload.getClass(), targetClass)) {
		try {
			return this.conversionService.convert(payload, targetClass);
		}
		catch (ConversionException ex) {
			throw new MessageConversionException(message, "Failed to convert message payload '" +
					payload + "' to '" + targetClass.getName() + "'", ex);
		}
	}
	return (ClassUtils.isAssignableValue(targetClass, payload) ? payload : null);
}
 
Example 4
Source File: AbstractPropertyResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Convert the given value to the specified target type, if necessary.
 * @param value the original property value
 * @param targetType the specified target type for property retrieval
 * @return the converted value, or the original value if no conversion
 * is necessary
 * @since 4.3.5
 */
@SuppressWarnings("unchecked")
@Nullable
protected <T> T convertValueIfNecessary(Object value, @Nullable Class<T> targetType) {
	if (targetType == null) {
		return (T) value;
	}
	ConversionService conversionServiceToUse = this.conversionService;
	if (conversionServiceToUse == null) {
		// Avoid initialization of shared DefaultConversionService if
		// no standard type conversion is needed in the first place...
		if (ClassUtils.isAssignableValue(targetType, value)) {
			return (T) value;
		}
		conversionServiceToUse = DefaultConversionService.getSharedInstance();
	}
	return conversionServiceToUse.convert(value, targetType);
}
 
Example 5
Source File: AbstractPropertyResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert the given value to the specified target type, if necessary.
 * @param value the original property value
 * @param targetType the specified target type for property retrieval
 * @return the converted value, or the original value if no conversion
 * is necessary
 * @since 4.3.5
 */
@SuppressWarnings("unchecked")
protected <T> T convertValueIfNecessary(Object value, Class<T> targetType) {
	if (targetType == null) {
		return (T) value;
	}
	ConversionService conversionServiceToUse = this.conversionService;
	if (conversionServiceToUse == null) {
		// Avoid initialization of shared DefaultConversionService if
		// no standard type conversion is needed in the first place...
		if (ClassUtils.isAssignableValue(targetType, value)) {
			return (T) value;
		}
		conversionServiceToUse = DefaultConversionService.getSharedInstance();
	}
	return conversionServiceToUse.convert(value, targetType);
}
 
Example 6
Source File: ExpressionUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determines if there is a type converter available in the specified context and
 * attempts to use it to convert the supplied value to the specified type. Throws an
 * exception if conversion is not possible.
 * @param context the evaluation context that may define a type converter
 * @param typedValue the value to convert and a type descriptor describing it
 * @param targetType the type to attempt conversion to
 * @return the converted value
 * @throws EvaluationException if there is a problem during conversion or conversion
 * of the value to the specified type is not supported
 */
@SuppressWarnings("unchecked")
@Nullable
public static <T> T convertTypedValue(
		@Nullable EvaluationContext context, TypedValue typedValue, @Nullable Class<T> targetType) {

	Object value = typedValue.getValue();
	if (targetType == null) {
		return (T) value;
	}
	if (context != null) {
		return (T) context.getTypeConverter().convertValue(
				value, typedValue.getTypeDescriptor(), TypeDescriptor.valueOf(targetType));
	}
	if (ClassUtils.isAssignableValue(targetType, value)) {
		return (T) value;
	}
	throw new EvaluationException("Cannot convert value '" + value + "' to type '" + targetType.getName() + "'");
}
 
Example 7
Source File: AbstractNamedValueMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
	Class<?> paramType = parameter.getParameterType();
	NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);

	Object arg = resolveArgumentInternal(parameter, message, namedValueInfo.name);
	if (arg == null) {
		if (namedValueInfo.defaultValue != null) {
			arg = resolveDefaultValue(namedValueInfo.defaultValue);
		}
		else if (namedValueInfo.required && !parameter.getParameterType().getName().equals("java.util.Optional")) {
			handleMissingValue(namedValueInfo.name, parameter, message);
		}
		arg = handleNullValue(namedValueInfo.name, arg, paramType);
	}
	else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
		arg = resolveDefaultValue(namedValueInfo.defaultValue);
	}

	if (!ClassUtils.isAssignableValue(paramType, arg)) {
		arg = this.conversionService.convert(
				arg, TypeDescriptor.valueOf(arg.getClass()), new TypeDescriptor(parameter));
	}

	handleResolvedValue(arg, namedValueInfo.name, parameter, message);

	return arg;
}
 
Example 8
Source File: ConstructorResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
public int getAssignabilityWeight(Class<?>[] paramTypes) {
	for (int i = 0; i < paramTypes.length; i++) {
		if (!ClassUtils.isAssignableValue(paramTypes[i], this.arguments[i])) {
			return Integer.MAX_VALUE;
		}
	}
	for (int i = 0; i < paramTypes.length; i++) {
		if (!ClassUtils.isAssignableValue(paramTypes[i], this.rawArguments[i])) {
			return Integer.MAX_VALUE - 512;
		}
	}
	return Integer.MAX_VALUE - 1024;
}
 
Example 9
Source File: KotlinJacksonBuildCustomizer.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(Build build) {
	boolean isKotlin = ClassUtils.isAssignableValue(KotlinLanguage.class, this.description.getLanguage());
	if (this.buildMetadataResolver.hasFacet(build, "json") && isKotlin) {
		build.dependencies().add("jackson-module-kotlin", "com.fasterxml.jackson.module", "jackson-module-kotlin",
				DependencyScope.COMPILE);
	}
}
 
Example 10
Source File: ConstructorResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public int getAssignabilityWeight(Class<?>[] paramTypes) {
	for (int i = 0; i < paramTypes.length; i++) {
		if (!ClassUtils.isAssignableValue(paramTypes[i], this.arguments[i])) {
			return Integer.MAX_VALUE;
		}
	}
	for (int i = 0; i < paramTypes.length; i++) {
		if (!ClassUtils.isAssignableValue(paramTypes[i], this.rawArguments[i])) {
			return Integer.MAX_VALUE - 512;
		}
	}
	return Integer.MAX_VALUE - 1024;
}
 
Example 11
Source File: AmazonS3ProxyFactory.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Factory-method to create a proxy using the {@link SimpleStorageRedirectInterceptor}
 * that supports redirects for buckets which are in a different region. This proxy
 * uses the amazonS3 parameter as a "prototype" and re-uses the credentials from the
 * passed in {@link AmazonS3} instance. Proxy implementations uses the
 * {@link AmazonS3ClientFactory} to create region specific clients, which are cached
 * by the implementation on a region basis to avoid unnecessary object creation.
 * @param amazonS3 Fully configured AmazonS3 client, the client can be an immutable
 * instance (created by the {@link com.amazonaws.services.s3.AmazonS3ClientBuilder})
 * as this proxy will not change the underlying implementation.
 * @return AOP-Proxy that intercepts all method calls using the
 * {@link SimpleStorageRedirectInterceptor}
 */
public static AmazonS3 createProxy(AmazonS3 amazonS3) {
	Assert.notNull(amazonS3, "AmazonS3 client must not be null");

	if (AopUtils.isAopProxy(amazonS3)) {

		Advised advised = (Advised) amazonS3;
		for (Advisor advisor : advised.getAdvisors()) {
			if (ClassUtils.isAssignableValue(SimpleStorageRedirectInterceptor.class,
					advisor.getAdvice())) {
				return amazonS3;
			}
		}

		try {
			advised.addAdvice(new SimpleStorageRedirectInterceptor(
					(AmazonS3) advised.getTargetSource().getTarget()));
		}
		catch (Exception e) {
			throw new RuntimeException(
					"Error adding advice for class amazonS3 instance", e);
		}

		return amazonS3;
	}

	ProxyFactory factory = new ProxyFactory(amazonS3);
	factory.setInterfaces(AmazonS3.class);
	factory.addAdvice(new SimpleStorageRedirectInterceptor(amazonS3));

	return (AmazonS3) factory.getProxy();
}
 
Example 12
Source File: RefreshScopeRefreshedEventListener.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
boolean isAssignable(String className, Object value) {
    try {
        return ClassUtils.isAssignableValue(ClassUtils.forName(className, null), value);
    } catch (ClassNotFoundException e) {
        return false;
    }
}
 
Example 13
Source File: AbstractWebArgumentResolverAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Delegate to the {@link WebArgumentResolver} instance.
 * @exception IllegalStateException if the resolved value is not assignable
 * to the method parameter.
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

	Class<?> paramType = parameter.getParameterType();
	Object result = this.adaptee.resolveArgument(parameter, webRequest);
	if (result == WebArgumentResolver.UNRESOLVED || !ClassUtils.isAssignableValue(paramType, result)) {
		throw new IllegalStateException(
				"Standard argument type [" + paramType.getName() + "] in method " + parameter.getMethod() +
				"resolved to incompatible value of type [" + (result != null ? result.getClass() : null) +
				"]. Consider declaring the argument type in a less specific fashion.");
	}
	return result;
}
 
Example 14
Source File: AspectJAfterReturningAdvice.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Following AspectJ semantics, if a return value is null (or return type is void),
 * then the return type of target method should be used to determine whether advice
 * is invoked or not. Also, even if the return type is void, if the type of argument
 * declared in the advice method is Object, then the advice must still get invoked.
 * @param type the type of argument declared in advice method
 * @param method the advice method
 * @param returnValue the return value of the target method
 * @return whether to invoke the advice method for the given return value and type
 */
private boolean matchesReturnValue(Class<?> type, Method method, @Nullable Object returnValue) {
	if (returnValue != null) {
		return ClassUtils.isAssignableValue(type, returnValue);
	}
	else if (Object.class == type && void.class == method.getReturnType()) {
		return true;
	}
	else {
		return ClassUtils.isAssignable(type, method.getReturnType());
	}
}
 
Example 15
Source File: AspectJAfterReturningAdvice.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Following AspectJ semantics, if a return value is null (or return type is void),
 * then the return type of target method should be used to determine whether advice
 * is invoked or not. Also, even if the return type is void, if the type of argument
 * declared in the advice method is Object, then the advice must still get invoked.
 * @param type the type of argument declared in advice method
 * @param method the advice method
 * @param returnValue the return value of the target method
 * @return whether to invoke the advice method for the given return value and type
 */
private boolean matchesReturnValue(Class<?> type, Method method, Object returnValue) {
	if (returnValue != null) {
		return ClassUtils.isAssignableValue(type, returnValue);
	}
	else if (Object.class == type && void.class == method.getReturnType()) {
		return true;
	}
	else{
		return ClassUtils.isAssignable(type, method.getReturnType());
	}
}
 
Example 16
Source File: ConfigurationClassEnhancer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private Object obtainBeanInstanceFromFactory(Method beanMethod, Object[] beanMethodArgs,
		ConfigurableBeanFactory beanFactory, String beanName) {

	// The user (i.e. not the factory) is requesting this bean through a call to
	// the bean method, direct or indirect. The bean may have already been marked
	// as 'in creation' in certain autowiring scenarios; if so, temporarily set
	// the in-creation status to false in order to avoid an exception.
	boolean alreadyInCreation = beanFactory.isCurrentlyInCreation(beanName);
	try {
		if (alreadyInCreation) {
			beanFactory.setCurrentlyInCreation(beanName, false);
		}
		boolean useArgs = !ObjectUtils.isEmpty(beanMethodArgs);
		if (useArgs && beanFactory.isSingleton(beanName)) {
			// Stubbed null arguments just for reference purposes,
			// expecting them to be autowired for regular singleton references?
			// A safe assumption since @Bean singleton arguments cannot be optional...
			for (Object arg : beanMethodArgs) {
				if (arg == null) {
					useArgs = false;
					break;
				}
			}
		}
		Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) :
				beanFactory.getBean(beanName));
		if (beanInstance != null && !ClassUtils.isAssignableValue(beanMethod.getReturnType(), beanInstance)) {
			String msg = String.format("@Bean method %s.%s called as a bean reference " +
						"for type [%s] but overridden by non-compatible bean instance of type [%s].",
						beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName(),
						beanMethod.getReturnType().getName(), beanInstance.getClass().getName());
			try {
				BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName);
				msg += " Overriding bean of same name declared in: " + beanDefinition.getResourceDescription();
			}
			catch (NoSuchBeanDefinitionException ex) {
				// Ignore - simply no detailed message then.
			}
			throw new IllegalStateException(msg);
		}
		Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod();
		if (currentlyInvoked != null) {
			String outerBeanName = BeanAnnotationHelper.determineBeanNameFor(currentlyInvoked);
			beanFactory.registerDependentBean(beanName, outerBeanName);
		}
		return beanInstance;
	}
	finally {
		if (alreadyInCreation) {
			beanFactory.setCurrentlyInCreation(beanName, true);
		}
	}
}
 
Example 17
Source File: ConfigurationClassEnhancer.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Enhance a {@link Bean @Bean} method to check the supplied BeanFactory for the
 * existence of this bean object.
 * @throws Throwable as a catch-all for any exception that may be thrown when invoking the
 * super implementation of the proxied method i.e., the actual {@code @Bean} method
 */
@Override
public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
			MethodProxy cglibMethodProxy) throws Throwable {

	ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
	String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);

	// Determine whether this bean is a scoped-proxy
	Scope scope = AnnotationUtils.findAnnotation(beanMethod, Scope.class);
	if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {
		String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName);
		if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
			beanName = scopedBeanName;
		}
	}

	// To handle the case of an inter-bean method reference, we must explicitly check the
	// container for already cached instances.

	// First, check to see if the requested bean is a FactoryBean. If so, create a subclass
	// proxy that intercepts calls to getObject() and returns any cached bean instance.
	// This ensures that the semantics of calling a FactoryBean from within @Bean methods
	// is the same as that of referring to a FactoryBean within XML. See SPR-6602.
	if (factoryContainsBean(beanFactory, BeanFactory.FACTORY_BEAN_PREFIX + beanName) &&
			factoryContainsBean(beanFactory, beanName)) {
		Object factoryBean = beanFactory.getBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName);
		if (factoryBean instanceof ScopedProxyFactoryBean) {
			// Pass through - scoped proxy factory beans are a special case and should not
			// be further proxied
		}
		else {
			// It is a candidate FactoryBean - go ahead with enhancement
			return enhanceFactoryBean(factoryBean, beanFactory, beanName);
		}
	}

	if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
		// The factory is calling the bean method in order to instantiate and register the bean
		// (i.e. via a getBean() call) -> invoke the super implementation of the method to actually
		// create the bean instance.
		if (BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
			logger.warn(String.format("@Bean method %s.%s is non-static and returns an object " +
					"assignable to Spring's BeanFactoryPostProcessor interface. This will " +
					"result in a failure to process annotations such as @Autowired, " +
					"@Resource and @PostConstruct within the method's declaring " +
					"@Configuration class. Add the 'static' modifier to this method to avoid " +
					"these container lifecycle issues; see @Bean javadoc for complete details.",
					beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
		}
		return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
	}
	else {
		// The user (i.e. not the factory) is requesting this bean through a
		// call to the bean method, direct or indirect. The bean may have already been
		// marked as 'in creation' in certain autowiring scenarios; if so, temporarily
		// set the in-creation status to false in order to avoid an exception.
		boolean alreadyInCreation = beanFactory.isCurrentlyInCreation(beanName);
		try {
			if (alreadyInCreation) {
				beanFactory.setCurrentlyInCreation(beanName, false);
			}
			Object beanInstance = (!ObjectUtils.isEmpty(beanMethodArgs) ?
					beanFactory.getBean(beanName, beanMethodArgs) : beanFactory.getBean(beanName));
			if (beanInstance != null && !ClassUtils.isAssignableValue(beanMethod.getReturnType(), beanInstance)) {
				String msg = String.format("@Bean method %s.%s called as a bean reference " +
							"for type [%s] but overridden by non-compatible bean instance of type [%s].",
							beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName(),
							beanMethod.getReturnType().getName(), beanInstance.getClass().getName());
				try {
					BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName);
					msg += " Overriding bean of same name declared in: " + beanDefinition.getResourceDescription();
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Ignore - simply no detailed message then.
				}
				throw new IllegalStateException(msg);
			}
			return beanInstance;
		}
		finally {
			if (alreadyInCreation) {
				beanFactory.setCurrentlyInCreation(beanName, true);
			}
		}
	}
}
 
Example 18
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 19
Source File: AbstractBeanFactory.java    From blog_demos with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException {
	String beanName = transformedBeanName(name);
	Class<?> typeToMatch = (targetType != null ? targetType : Object.class);

	// Check manually registered singletons.
	Object beanInstance = getSingleton(beanName, false);
	if (beanInstance != null) {
		if (beanInstance instanceof FactoryBean) {
			if (!BeanFactoryUtils.isFactoryDereference(name)) {
				Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
				return (type != null && ClassUtils.isAssignable(typeToMatch, type));
			}
			else {
				return ClassUtils.isAssignableValue(typeToMatch, beanInstance);
			}
		}
		else {
			return !BeanFactoryUtils.isFactoryDereference(name) &&
					ClassUtils.isAssignableValue(typeToMatch, beanInstance);
		}
	}
	else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
		// null instance registered
		return false;
	}

	else {
		// No singleton instance found -> check bean definition.
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// No bean definition found in this factory -> delegate to parent.
			return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType);
		}

		// Retrieve corresponding bean definition.
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

		Class<?>[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ?
				new Class<?>[] {typeToMatch} : new Class<?>[] {FactoryBean.class, typeToMatch});

		// Check decorated bean definition, if any: We assume it'll be easier
		// to determine the decorated bean's type than the proxy's type.
		BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
		if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
			RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
			Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
			if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
				return typeToMatch.isAssignableFrom(targetClass);
			}
		}

		Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);
		if (beanType == null) {
			return false;
		}

		// Check bean class whether we're dealing with a FactoryBean.
		if (FactoryBean.class.isAssignableFrom(beanType)) {
			if (!BeanFactoryUtils.isFactoryDereference(name)) {
				// If it's a FactoryBean, we want to look at what it creates, not the factory class.
				beanType = getTypeForFactoryBean(beanName, mbd);
				if (beanType == null) {
					return false;
				}
			}
		}
		else if (BeanFactoryUtils.isFactoryDereference(name)) {
			// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
			// type but we nevertheless are being asked to dereference a FactoryBean...
			// Let's check the original bean class and proceed with it if it is a FactoryBean.
			beanType = predictBeanType(beanName, mbd, FactoryBean.class);
			if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {
				return false;
			}
		}

		return typeToMatch.isAssignableFrom(beanType);
	}
}
 
Example 20
Source File: AppRoleAuthentication.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
private Map<String, String> getAppRoleLoginBody(RoleId roleId, SecretId secretId) {

		Map<String, String> login = new HashMap<>();

		login.put("role_id", getRoleId(roleId));

		if (!ClassUtils.isAssignableValue(AbsentSecretId.class, secretId)) {
			login.put("secret_id", getSecretId(secretId));
		}

		return login;
	}