Springboot 提供了很多转化器:
其中有ApplicationConversionService:extends FormattingConversionService。
public static void addApplicationConverters(ConverterRegistry registry) {
addDelimitedStringConverters(registry);
registry.addConverter(new StringToDurationConverter());
registry.addConverter(new DurationToStringConverter());
registry.addConverter(new NumberToDurationConverter());
registry.addConverter(new DurationToNumberConverter());
registry.addConverter(new StringToPeriodConverter());
registry.addConverter(new PeriodToStringConverter());
registry.addConverter(new NumberToPeriodConverter());
registry.addConverter(new StringToDataSizeConverter());
registry.addConverter(new NumberToDataSizeConverter());
registry.addConverter(new StringToFileConverter());
registry.addConverter(new InputStreamSourceToByteArrayConverter());
registry.addConverterFactory(new LenientStringToEnumConverterFactory());
registry.addConverterFactory(new LenientBooleanToEnumConverterFactory());
if (registry instanceof ConversionService conversionService) {
addApplicationConverters(registry, conversionService);
}
}
private static void addApplicationConverters(ConverterRegistry registry, ConversionService conversionService) {
registry.addConverter(new CharSequenceToObjectConverter(conversionService));
}
转化为一个数组为delimited String.
final class ArrayToDelimitedStringConverter implements ConditionalGenericConverter {
private final CollectionToDelimitedStringConverter delegate;
ArrayToDelimitedStringConverter(ConversionService conversionService) {
this.delegate = new CollectionToDelimitedStringConverter(conversionService);
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object[].class, String.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return this.delegate.matches(sourceType, targetType);
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
List<Object> list = Arrays.asList(ObjectUtils.toObjectArray(source));
return this.delegate.convert(list, sourceType, targetType);
}
}
本质上就是各种数据类型之间的转化: