Support java.util.Optional for @MVC named value args

After this change, java.util.Optional is supported with @RequestParam,
@RequestHeader, and @MatrixVariable arguments in Java 8. When Optional
is used the required flag is effectively ignored.

Issue: SPR-11829
This commit is contained in:
Rossen Stoyanchev
2014-06-12 23:50:26 -04:00
parent c2356e57c8
commit 0dc6082b01
9 changed files with 185 additions and 10 deletions

View File

@@ -37,6 +37,10 @@ import org.springframework.util.ClassUtils;
*/
public class DefaultConversionService extends GenericConversionService {
/** Java 8's java.util.Optional class available? */
private static final boolean javaUtilOptionalClassAvailable =
ClassUtils.isPresent("java.util.Optional", DefaultConversionService.class.getClassLoader());
/** Java 8's java.time package available? */
private static final boolean jsr310Available =
ClassUtils.isPresent("java.time.ZoneId", DefaultConversionService.class.getClassLoader());
@@ -71,6 +75,9 @@ public class DefaultConversionService extends GenericConversionService {
converterRegistry.addConverter(new ObjectToObjectConverter());
converterRegistry.addConverter(new IdToEntityConverter((ConversionService) converterRegistry));
converterRegistry.addConverter(new FallbackObjectToStringConverter());
if (javaUtilOptionalClassAvailable) {
converterRegistry.addConverter(new ObjectToOptionalConverter((ConversionService) converterRegistry));
}
}
// internal helpers

View File

@@ -59,6 +59,9 @@ import org.springframework.util.StringUtils;
*/
public class GenericConversionService implements ConfigurableConversionService {
/** Java 8's java.util.Optional.empty() */
private static Object javaUtilOptionalEmpty = null;
/**
* General NO-OP converter used when conversion is not required.
*/
@@ -70,6 +73,15 @@ public class GenericConversionService implements ConfigurableConversionService {
*/
private static final GenericConverter NO_MATCH = new NoOpConverter("NO_MATCH");
static {
try {
Class<?> clazz = ClassUtils.forName("java.util.Optional", GenericConversionService.class.getClassLoader());
javaUtilOptionalEmpty = ClassUtils.getMethod(clazz, "empty").invoke(null);
} catch (Exception ex) {
// Java 8 not available - conversion to Optional not supported then.
}
}
private final Converters converters = new Converters();
@@ -204,13 +216,18 @@ public class GenericConversionService implements ConfigurableConversionService {
/**
* Template method to convert a null source.
* <p>Default implementation returns {@code null}.
* <p>Default implementation returns {@code null} or the Java 8
* {@link java.util.Optional#empty()} instance if the target type is
* {@code java.uti.Optional}.
* Subclasses may override to return custom null objects for specific target types.
* @param sourceType the sourceType to convert from
* @param targetType the targetType to convert to
* @return the converted null object
*/
protected Object convertNullSource(TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.getObjectType().equals(javaUtilOptionalEmpty.getClass())) {
return javaUtilOptionalEmpty;
}
return null;
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.convert.support;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
/**
* Convert an Object to {@code java.util.Optional<T>} if necessary using the
* {@code ConversionService} to convert the source Object to the generic type
* of Optional when known.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
final class ObjectToOptionalConverter implements ConditionalGenericConverter {
private final ConversionService conversionService;
public ObjectToOptionalConverter(ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, Optional.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.getResolvableType() != null) {
return this.conversionService.canConvert(sourceType, new GenericTypeDescriptor(targetType));
}
else {
return true;
}
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return Optional.empty();
}
if (targetType.getResolvableType() == null) {
return Optional.of(source);
}
else {
Object target = this.conversionService.convert(source, sourceType, new GenericTypeDescriptor(targetType));
return Optional.of(target);
}
}
@SuppressWarnings("serial")
private static class GenericTypeDescriptor extends TypeDescriptor {
public GenericTypeDescriptor(TypeDescriptor typeDescriptor) {
super(typeDescriptor.getResolvableType().getGeneric(0), null, typeDescriptor.getAnnotations());
}
}
}