org.springframework.beans.factory.InjectionPoint Java Examples

The following examples show how to use org.springframework.beans.factory.InjectionPoint. 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: 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 #2
Source File: ConstructorResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
static InjectionPoint setCurrentInjectionPoint(@Nullable InjectionPoint injectionPoint) {
	InjectionPoint old = currentInjectionPoint.get();
	if (injectionPoint != null) {
		currentInjectionPoint.set(injectionPoint);
	}
	else {
		currentInjectionPoint.remove();
	}
	return old;
}
 
Example #3
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {
	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		return getBean(name, descriptor.getDependencyType());
	}
	finally {
		ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
	}
}
 
Example #4
Source File: ReactiveConfiguration.java    From mcspring-boot with MIT License 5 votes vote down vote up
@Scope(SCOPE_PROTOTYPE)
@Bean
public <T extends Event> Observable<T> eventObservable(InjectionPoint injectionPoint, Plugin plugin, Context context) {
    val observeEvent = injectionPoint.getAnnotation(ObserveEvent.class);
    if (observeEvent == null) return null;
    val eventType = ((DependencyDescriptor) injectionPoint).getResolvableType().getGeneric(0);
    val eventEmitter = new EventEmitter<T>((Class<? extends Event>) eventType.getRawClass(), observeEvent, plugin, context);
    return Observable.create(eventEmitter)
            .doOnSubscribe(compositeDisposable::add)
            .doOnDispose(() -> HandlerList.unregisterAll(eventEmitter.getListener()));
}
 
Example #5
Source File: ResourceConfiguration.java    From mcspring-boot with MIT License 5 votes vote down vote up
@Scope(SCOPE_PROTOTYPE)
@Bean
public Instance configInstance(InjectionPoint injectionPoint, ConversionService conversionService, Environment environment) {
    val dynamicValue = injectionPoint.getAnnotation(DynamicValue.class);
    val type = ((DependencyDescriptor) injectionPoint).getResolvableType().getGeneric(0);

    return new Instance(environment, dynamicValue.value(), conversionService, type.getRawClass());
}
 
Example #6
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 #7
Source File: ConstructorResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
static InjectionPoint setCurrentInjectionPoint(@Nullable InjectionPoint injectionPoint) {
	InjectionPoint old = currentInjectionPoint.get();
	if (injectionPoint != null) {
		currentInjectionPoint.set(injectionPoint);
	}
	else {
		currentInjectionPoint.remove();
	}
	return old;
}
 
Example #8
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {
	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		return getBean(name, descriptor.getDependencyType());
	}
	finally {
		ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
	}
}
 
Example #9
Source File: ConstructorResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static InjectionPoint setCurrentInjectionPoint(InjectionPoint injectionPoint) {
	InjectionPoint old = currentInjectionPoint.get();
	if (injectionPoint != null) {
		currentInjectionPoint.set(injectionPoint);
	}
	else {
		currentInjectionPoint.remove();
	}
	return old;
}
 
Example #10
Source File: ConstructorResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Template method for resolving the specified argument which is supposed to be autowired.
 */
protected Object resolveAutowiredArgument(
		MethodParameter param, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) {

	if (InjectionPoint.class.isAssignableFrom(param.getParameterType())) {
		InjectionPoint injectionPoint = currentInjectionPoint.get();
		if (injectionPoint == null) {
			throw new IllegalStateException("No current InjectionPoint available for " + param);
		}
		return injectionPoint;
	}
	return this.beanFactory.resolveDependency(
			new DependencyDescriptor(param, true), beanName, autowiredBeanNames, typeConverter);
}
 
Example #11
Source File: ConstructorResolver.java    From lams with GNU General Public License v2.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) {

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

	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) {
			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 #12
Source File: ComposedMappingConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
@Scope("prototype")
public Logger logger(InjectionPoint injectionPoint) {
    return LogManager.getLogger(injectionPoint.getField().getDeclaringClass());
}
 
Example #13
Source File: ConfigurationClassProcessingTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Bean @Scope("prototype")
public TestBean adaptive1(InjectionPoint ip) {
	return new TestBean(ip.getMember().getName());
}
 
Example #14
Source File: InjectBeanPostProcessor.java    From spring-boot-starter-dubbo with Apache License 2.0 4 votes vote down vote up
@Override
protected void inject(Object bean, String beanName, 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<String>(1);
		TypeConverter typeConverter = beanFactory.getTypeConverter();
		try {
			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)) {
							if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
								this.cachedFieldValue = new ShortcutDependencyDescriptor(
										desc, autowiredBeanName, field.getType());
							}
						}
					}
				}
				else {
					this.cachedFieldValue = null;
				}
				this.cached = true;
			}
		}
	}
	if (value != null) {
		ReflectionUtils.makeAccessible(field);
		field.set(bean, value);
	}
}
 
Example #15
Source File: LoggerConfig.java    From fake-smtp-server with Apache License 2.0 4 votes vote down vote up
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Logger logger(InjectionPoint ip){
    return LoggerFactory.getLogger(ip.getMember().getDeclaringClass());
}
 
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: AutowiredAnnotationBeanPostProcessor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void inject(Object bean, String beanName, 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<String>(1);
		TypeConverter typeConverter = beanFactory.getTypeConverter();
		try {
			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)) {
							if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
								this.cachedFieldValue = new ShortcutDependencyDescriptor(
										desc, autowiredBeanName, field.getType());
							}
						}
					}
				}
				else {
					this.cachedFieldValue = null;
				}
				this.cached = true;
			}
		}
	}
	if (value != null) {
		ReflectionUtils.makeAccessible(field);
		field.set(bean, value);
	}
}
 
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: AutowiredAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 4 votes vote down vote up
@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 {
			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;
			}
		}
	}
	if (value != null) {
		ReflectionUtils.makeAccessible(field);
		field.set(bean, value);
	}
}
 
Example #20
Source File: ConfigurationClassProcessingTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Bean @Scope("prototype")
public TestBean adaptive1(InjectionPoint ip) {
	return new TestBean(ip.getMember().getName());
}
 
Example #21
Source File: DefaultListableBeanFactory.java    From spring-analysis-note 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 #22
Source File: AutowiredAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@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 {
			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;
			}
		}
	}
	if (value != null) {
		ReflectionUtils.makeAccessible(field);
		field.set(bean, value);
	}
}