org.springframework.beans.TypeConverter Java Examples

The following examples show how to use org.springframework.beans.TypeConverter. 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: 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 #2
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 #3
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
		Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

	descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
	if (javaUtilOptionalClass == descriptor.getDependencyType()) {
		return new OptionalDependencyFactory().createOptionalDependency(descriptor, requestingBeanName);
	}
	else if (ObjectFactory.class == descriptor.getDependencyType() ||
			ObjectProvider.class == descriptor.getDependencyType()) {
		return new DependencyObjectProvider(descriptor, requestingBeanName);
	}
	else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
		return new Jsr330ProviderFactory().createDependencyProvider(descriptor, requestingBeanName);
	}
	else {
		Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
				descriptor, requestingBeanName);
		if (result == null) {
			result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
		}
		return result;
	}
}
 
Example #4
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
	if (Optional.class == descriptor.getDependencyType()) {
		return createOptionalDependency(descriptor, requestingBeanName);
	}
	else if (ObjectFactory.class == descriptor.getDependencyType() ||
			ObjectProvider.class == descriptor.getDependencyType()) {
		return new DependencyObjectProvider(descriptor, requestingBeanName);
	}
	else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
		return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
	}
	else {
		Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
				descriptor, requestingBeanName);
		if (result == null) {
			result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
		}
		return result;
	}
}
 
Example #5
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 #6
Source File: DefaultListableBeanFactory.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveDependency(DependencyDescriptor descriptor, String beanName,
		Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

	descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
	if (descriptor.getDependencyType().equals(ObjectFactory.class)) {
		return new DependencyObjectFactory(descriptor, beanName);
	}
	else if (descriptor.getDependencyType().equals(javaxInjectProviderClass)) {
		return new DependencyProviderFactory().createDependencyProvider(descriptor, beanName);
	}
	else {
		Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, beanName);
		if (result == null) {
			result = doResolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
		}
		return result;
	}
}
 
Example #7
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
	if (Optional.class == descriptor.getDependencyType()) {
		return createOptionalDependency(descriptor, requestingBeanName);
	}
	else if (ObjectFactory.class == descriptor.getDependencyType() ||
			ObjectProvider.class == descriptor.getDependencyType()) {
		return new DependencyObjectProvider(descriptor, requestingBeanName);
	}
	else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
		return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
	}
	else {
		Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
				descriptor, requestingBeanName);
		if (result == null) {
			result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
		}
		return result;
	}
}
 
Example #8
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 #9
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 #10
Source File: AbstractFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtain a bean type converter from the BeanFactory that this bean
 * runs in. This is typically a fresh instance for each call,
 * since TypeConverters are usually <i>not</i> thread-safe.
 * <p>Falls back to a SimpleTypeConverter when not running in a BeanFactory.
 * @see ConfigurableBeanFactory#getTypeConverter()
 * @see org.springframework.beans.SimpleTypeConverter
 */
protected TypeConverter getBeanTypeConverter() {
	BeanFactory beanFactory = getBeanFactory();
	if (beanFactory instanceof ConfigurableBeanFactory) {
		return ((ConfigurableBeanFactory) beanFactory).getTypeConverter();
	}
	else {
		return new SimpleTypeConverter();
	}
}
 
Example #11
Source File: ListFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected List<Object> createInstance() {
	if (this.sourceList == null) {
		throw new IllegalArgumentException("'sourceList' is required");
	}
	List<Object> result = null;
	if (this.targetListClass != null) {
		result = BeanUtils.instantiateClass(this.targetListClass);
	}
	else {
		result = new ArrayList<Object>(this.sourceList.size());
	}
	Class<?> valueType = null;
	if (this.targetListClass != null) {
		valueType = ResolvableType.forClass(this.targetListClass).asCollection().resolveGeneric();
	}
	if (valueType != null) {
		TypeConverter converter = getBeanTypeConverter();
		for (Object elem : this.sourceList) {
			result.add(converter.convertIfNecessary(elem, valueType));
		}
	}
	else {
		result.addAll(this.sourceList);
	}
	return result;
}
 
Example #12
Source File: BeanDefinitionValueResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a BeanDefinitionValueResolver for the given BeanFactory and BeanDefinition.
 * @param beanFactory the BeanFactory to resolve against
 * @param beanName the name of the bean that we work on
 * @param beanDefinition the BeanDefinition of the bean that we work on
 * @param typeConverter the TypeConverter to use for resolving TypedStringValues
 */
public BeanDefinitionValueResolver(
		AbstractBeanFactory beanFactory, String beanName, BeanDefinition beanDefinition, TypeConverter typeConverter) {

	this.beanFactory = beanFactory;
	this.beanName = beanName;
	this.beanDefinition = beanDefinition;
	this.typeConverter = typeConverter;
}
 
Example #13
Source File: AbstractAutowireCapableBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert the given value for the specified target property.
 */
private Object convertForProperty(Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {
	if (converter instanceof BeanWrapperImpl) {
		return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
	}
	else {
		PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
		MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
		return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
	}
}
 
Example #14
Source File: SetFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Set<Object> createInstance() {
	if (this.sourceSet == null) {
		throw new IllegalArgumentException("'sourceSet' is required");
	}
	Set<Object> result = null;
	if (this.targetSetClass != null) {
		result = BeanUtils.instantiateClass(this.targetSetClass);
	}
	else {
		result = new LinkedHashSet<Object>(this.sourceSet.size());
	}
	Class<?> valueType = null;
	if (this.targetSetClass != null) {
		valueType = ResolvableType.forClass(this.targetSetClass).asCollection().resolveGeneric();
	}
	if (valueType != null) {
		TypeConverter converter = getBeanTypeConverter();
		for (Object elem : this.sourceSet) {
			result.add(converter.convertIfNecessary(elem, valueType));
		}
	}
	else {
		result.addAll(this.sourceSet);
	}
	return result;
}
 
Example #15
Source File: AbstractBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypeConverter getTypeConverter() {
	TypeConverter customConverter = getCustomTypeConverter();
	if (customConverter != null) {
		return customConverter;
	}
	else {
		// Build default TypeConverter, registering custom editors.
		SimpleTypeConverter typeConverter = new SimpleTypeConverter();
		typeConverter.setConversionService(getConversionService());
		registerCustomEditors(typeConverter);
		return typeConverter;
	}
}
 
Example #16
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 #17
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 #18
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 #19
Source File: AbstractAutowireCapableBeanFactory.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the given value for the specified target property.
 */
private Object convertForProperty(Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {
	if (converter instanceof BeanWrapperImpl) {
		return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
	}
	else {
		PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
		MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
		return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
	}
}
 
Example #20
Source File: ArgumentConvertingMethodInvoker.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return the TypeConverter used for argument type conversion.
 * <p>Can be cast to {@link org.springframework.beans.PropertyEditorRegistry}
 * if direct access to the underlying PropertyEditors is desired
 * (provided that the present TypeConverter actually implements the
 * PropertyEditorRegistry interface).
 */
@Nullable
public TypeConverter getTypeConverter() {
	if (this.typeConverter == null && this.useDefaultConverter) {
		this.typeConverter = getDefaultTypeConverter();
	}
	return this.typeConverter;
}
 
Example #21
Source File: MethodInvokingBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtain the TypeConverter from the BeanFactory that this bean runs in,
 * if possible.
 * @see ConfigurableBeanFactory#getTypeConverter()
 */
@Override
protected TypeConverter getDefaultTypeConverter() {
	if (this.beanFactory != null) {
		return this.beanFactory.getTypeConverter();
	}
	else {
		return super.getDefaultTypeConverter();
	}
}
 
Example #22
Source File: MethodInvokingBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Obtain the TypeConverter from the BeanFactory that this bean runs in,
 * if possible.
 * @see ConfigurableBeanFactory#getTypeConverter()
 */
@Override
protected TypeConverter getDefaultTypeConverter() {
	if (this.beanFactory != null) {
		return this.beanFactory.getTypeConverter();
	}
	else {
		return super.getDefaultTypeConverter();
	}
}
 
Example #23
Source File: MapFactoryBean.java    From java-technology-stack with MIT License 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<>(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 #24
Source File: SetFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Set<Object> createInstance() {
	if (this.sourceSet == null) {
		throw new IllegalArgumentException("'sourceSet' is required");
	}
	Set<Object> result = null;
	if (this.targetSetClass != null) {
		result = BeanUtils.instantiateClass(this.targetSetClass);
	}
	else {
		result = new LinkedHashSet<>(this.sourceSet.size());
	}
	Class<?> valueType = null;
	if (this.targetSetClass != null) {
		valueType = ResolvableType.forClass(this.targetSetClass).asCollection().resolveGeneric();
	}
	if (valueType != null) {
		TypeConverter converter = getBeanTypeConverter();
		for (Object elem : this.sourceSet) {
			result.add(converter.convertIfNecessary(elem, valueType));
		}
	}
	else {
		result.addAll(this.sourceSet);
	}
	return result;
}
 
Example #25
Source File: AbstractFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Obtain a bean type converter from the BeanFactory that this bean
 * runs in. This is typically a fresh instance for each call,
 * since TypeConverters are usually <i>not</i> thread-safe.
 * <p>Falls back to a SimpleTypeConverter when not running in a BeanFactory.
 * @see ConfigurableBeanFactory#getTypeConverter()
 * @see org.springframework.beans.SimpleTypeConverter
 */
protected TypeConverter getBeanTypeConverter() {
	BeanFactory beanFactory = getBeanFactory();
	if (beanFactory instanceof ConfigurableBeanFactory) {
		return ((ConfigurableBeanFactory) beanFactory).getTypeConverter();
	}
	else {
		return new SimpleTypeConverter();
	}
}
 
Example #26
Source File: ListFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected List<Object> createInstance() {
	if (this.sourceList == null) {
		throw new IllegalArgumentException("'sourceList' is required");
	}
	List<Object> result = null;
	if (this.targetListClass != null) {
		result = BeanUtils.instantiateClass(this.targetListClass);
	}
	else {
		result = new ArrayList<>(this.sourceList.size());
	}
	Class<?> valueType = null;
	if (this.targetListClass != null) {
		valueType = ResolvableType.forClass(this.targetListClass).asCollection().resolveGeneric();
	}
	if (valueType != null) {
		TypeConverter converter = getBeanTypeConverter();
		for (Object elem : this.sourceList) {
			result.add(converter.convertIfNecessary(elem, valueType));
		}
	}
	else {
		result.addAll(this.sourceList);
	}
	return result;
}
 
Example #27
Source File: BeanDefinitionValueResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a BeanDefinitionValueResolver for the given BeanFactory and BeanDefinition.
 * @param beanFactory the BeanFactory to resolve against
 * @param beanName the name of the bean that we work on
 * @param beanDefinition the BeanDefinition of the bean that we work on
 * @param typeConverter the TypeConverter to use for resolving TypedStringValues
 */
public BeanDefinitionValueResolver(
		AbstractBeanFactory beanFactory, String beanName, BeanDefinition beanDefinition, TypeConverter typeConverter) {

	this.beanFactory = beanFactory;
	this.beanName = beanName;
	this.beanDefinition = beanDefinition;
	this.typeConverter = typeConverter;
}
 
Example #28
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Abstract method defining "autowire by type" (bean properties by type) behavior.
 * <p>This is like PicoContainer default, in which there must be exactly one bean
 * of the property type in the bean factory. This makes bean factories simple to
 * configure for small namespaces, but doesn't work as well as standard Spring
 * behavior for bigger applications.
 * @param beanName the name of the bean to autowire by type
 * @param mbd the merged bean definition to update through autowiring
 * @param bw the BeanWrapper from which we can obtain information about the bean
 * @param pvs the PropertyValues to register wired objects with
 */
protected void autowireByType(
		String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

	TypeConverter converter = getCustomTypeConverter();
	if (converter == null) {
		converter = bw;
	}

	Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
	String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
	for (String propertyName : propertyNames) {
		try {
			PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
			// Don't try autowiring by type for type Object: never makes sense,
			// even if it technically is a unsatisfied, non-simple property.
			if (Object.class != pd.getPropertyType()) {
				MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
				// Do not allow eager init for type matching in case of a prioritized post-processor.
				boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
				DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
				Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
				if (autowiredArgument != null) {
					pvs.add(propertyName, autowiredArgument);
				}
				for (String autowiredBeanName : autowiredBeanNames) {
					registerDependentBean(autowiredBeanName, beanName);
					if (logger.isTraceEnabled()) {
						logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
								propertyName + "' to bean named '" + autowiredBeanName + "'");
					}
				}
				autowiredBeanNames.clear();
			}
		}
		catch (BeansException ex) {
			throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
		}
	}
}
 
Example #29
Source File: MethodInvokingFactoryBean.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain the TypeConverter from the BeanFactory that this bean runs in,
 * if possible.
 * @see ConfigurableBeanFactory#getTypeConverter()
 */
@Override
protected TypeConverter getDefaultTypeConverter() {
	if (this.beanFactory != null) {
		return this.beanFactory.getTypeConverter();
	}
	else {
		return super.getDefaultTypeConverter();
	}
}
 
Example #30
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();
	}
}