Spring ConversionService 类型转换(一)Converter
Spring ConversionService 类型转换(一)Converter
Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html)
Spring ConversionService 类型转换系列文章:
JDK 提供的 PropertyEditor 只能将 String 类型转为 Object,如果要将一种 Object 类型转换成另一种 Object 类型就只能使用 Spring 提供的 ConversionService 了,这些类都位于 org.springframework.core.convert 包下。
一、ConversionService 使用
private ConversionService conversionService;
@Before
public void before() {
conversionService = new DefaultConversionService();
}
@Test
public void test() {
ConversionService conversionService = new DefaultConversionService();
Integer value = conversionService.convert("1", Integer.class);
Assert.assertTrue(value == 1);
}
在 DefaultConversionService 组件中已经注册了 Spring 默认的觉转换器,可以分为以下几类:
Converter一对一转换,把 S 类型转化成 T 类型,最常用的转换器ConverterFactory一对 N 转换GenericConverterN 对 N 转换
二、三种转换器

2.1 Converter(1:1)
(1) 接口
@FunctionalInterface
public interface Converter<S, T> {
T convert(S source);
}
Converter接口很简单,就是把 S 类型转化成 T 类型。我们看一下使用方法:
(2) 测试
@Test
public void converterTest() {
// ObjectToStringConverter
Assert.assertEquals("false", conversionService.convert(false, String.class));
// StringToBooleanConverter
Assert.assertTrue(conversionService.convert("true", Boolean.class));
}
(3) ObjectToStringConverter 分析
ObjectToStringConverter 和 StringToBooleanConverter 都是在 DefaultConversionService 中内置的。
final class ObjectToStringConverter implements Converter<Object, String> {
@Override
public String convert(Object source) {
return source.toString();
}
}
2.2 ConverterFactory(1:N)
(1) 接口
public interface ConverterFactory<S, R> {
<T extends R> Converter<S, T> getConverter(Class<T> targetType);
}
R 的子类都可以统一由这个 ConverterFactory 进行转换。
(2) 测试
// 测试 ConverterFactory StringToNumberConverterFactory
@Test
public void converterFactoryTest() {
Assert.assertTrue(conversionService.convert("1.2", double.class) == 1.2d);
Assert.assertTrue(conversionService.convert("1", int.class) == 1);
Assert.assertTrue(conversionService.convert("0x10", byte.class) == 0x10);
}
这里用到了 StringToNumberConverterFactory 把 String 转化成了 Number 的各个子类型,代码其实很简单:
(3) StringToNumberConverterFactory 分析
final class StringToNumberConverterFactory implements ConverterFactory<String, Number> {
@Override
public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToNumber<>(targetType);
}
private static final class StringToNumber<T extends Number> implements Converter<String, T> {
private final Class<T> targetType;
public StringToNumber(Class<T> targetType) {
this.targetType = targetType;
}
@Override
public T convert(String source) {
if (source.isEmpty()) {
return null;
}
// String 类型转换成 Number
return NumberUtils.parseNumber(source, this.targetType);
}
}
}
2.3 GenericConverter(N:N)
(1) 接口
public interface GenericConverter {
// 可以转换的类型
Set<ConvertiblePair> getConvertibleTypes();
Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType);
final class ConvertiblePair {
private final Class<?> sourceType;
private final Class<?> targetType;
}
}
// 匹配 GenericConverter
public interface ConditionalConverter {
boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType);
}
public interface ConditionalGenericConverter extends GenericConverter, ConditionalConverter {
}
GenericConverter 是 N:N 的转化,支持转化的所有类型都写在了属性 Set 内。
(2) 测试
// 测试 GenericConverter CollectionToCollectionConverter
@Test
public void genericConverterTest() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Set<String> set = (Set<String>) conversionService.convert(list,
TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class)),
TypeDescriptor.collection(Set.class, TypeDescriptor.valueOf(String.class)));
// List<Integer> -> Set<String>
Assert.assertEquals("1", set.toArray(new String[0])[0]);
}
这里用到了 CollectionToCollectionConverter
(3) CollectionToCollectionConverter 分析
final class CollectionToCollectionConverter implements ConditionalGenericConverter {
private final ConversionService conversionService;
public CollectionToCollectionConverter(ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Collection.class, Collection.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return ConversionUtils.canConvertElements(
sourceType.getElementTypeDescriptor(), targetType.getElementTypeDescriptor(), this.conversionService);
}
@Override
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
Collection<?> sourceCollection = (Collection<?>) source;
// 集合类型
boolean copyRequired = !targetType.getType().isInstance(source);
// 1. targetType 集合类型没变,不用转换
if (!copyRequired && sourceCollection.isEmpty()) {
return source;
}
// 集合元素类型
TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
// 2. targetType 集合元素没有指定类型,即 Object,且集合类型没变
if (elementDesc == null && !copyRequired) {
return source;
}
// 创建一个空集合
Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
(elementDesc != null ? elementDesc.getType() : null), sourceCollection.size());
// 3. targetType 集合元素没有指定类型,则元素不用转换类型
if (elementDesc == null) {
target.addAll(sourceCollection);
// 4. conversionService 将 sourceElement 转换为 targetElement 类型
} else {
for (Object sourceElement : sourceCollection) {
Object targetElement = this.conversionService.convert(sourceElement,
sourceType.elementTypeDescriptor(sourceElement), elementDesc);
target.add(targetElement);
if (sourceElement != targetElement) {
copyRequired = true;
}
}
}
return (copyRequired ? target : source);
}
}
参考:
- 《Spring 学习记录 3 ConversionService》:https://www.cnblogs.com/abcwt112/p/7447435.html
每天用心记录一点点。内容也许不重要,但习惯很重要!
Spring ConversionService 类型转换(一)Converter的更多相关文章
- Spring ConversionService 类型转换(二) ConversionService
Spring ConversionService 类型转换(二) ConversionService Spring 系列目录(https://www.cnblogs.com/binarylei/p/1 ...
- Spring类型转换(Converter)
Spring的类型转换 以前在面试中就有被问到关于spring数据绑定方面的问题,当时对它一直只是朦朦胧胧的概念,最近稍微闲下来有时间看了一下其中数据转换相关的内容,把相应的内容做个记录. 下面先说明 ...
- spring 之 类型转换
在spring中, 提供了至少三种的 类型转换方式: ConversionServiceFactoryBean, FormattingConversionServiceFactoryBean, C ...
- spring自动类型转换========Converter和PropertyEditor
Spring有两种自动类型转换器,一种是Converter,一种是propertyEditor. 两者的区别:Converter是类型转换成类型,Editor:从string类型转换为其他类型. 从某 ...
- Spring MVC 类型转换
SpringMVC类型转换: 1 日期类型转换: private Date birthday; <label for="">生日:<input type=&quo ...
- 2. Spring早期类型转换,基于PropertyEditor实现
青年时种下什么,老年时就收获什么.关注公众号[BAT的乌托邦],有Spring技术栈.MyBatis.JVM.中间件等小而美的原创专栏供以免费学习.分享.成长,拒绝浅尝辄止.本文已被 https:// ...
- Spring MVC类型转换
类型转换器引入 为什么页面上输入"12",可以赋值给Handler方法对应的参数?这是因为框架内部帮我们做了类型转换的工作.将String转换成int 但默认类型转换器并不是可以将 ...
- spring 之 类型转换 2
spring内置的转换器 在spring xml 文件中,配置属性的时候, 不管实际是 list 还是map ,还是Date, 或者原生的java 类型, 我们只能配置xml 给它们. 那么 spri ...
- 解决Spring MVC报No converter found for return value of type:class java.util.ArrayList问题
一.背景 在搭建一套Spring+SpringMVC+Mybatis(SSM)的环境(搭建步骤会在以后博客中给出),结果运行 程序时,适用@ResponseBody注解进行返回List<对象&g ...
随机推荐
- sqlite 时间戳转时间
), 'unixepoch','localtime') from messages where data != '' order by timestamp desc 官方eg: Examples Co ...
- Spring Boot Maven 打包 Jar
Maven pom.xml 必须包含 <packaging>jar</packaging> <build> <plugins> <plugin&g ...
- Java中构造函数传参数在基本数据类型和引用类型之间的区别
Java中构造函数传参数在基本数据类型和引用类型的区别 如果构造函数中穿的参数为基本数据类型,如果在函数中没有返回值,在调用的时候不会发生改变:而如果是引用类型,改变的是存储的位置,所有不管有没有返回 ...
- Multiple APK Support
[Multiple APK Support] Multiple APK support is a feature on Google Play that allows you to publish d ...
- flashfxp key密钥
flashfxp3.41中文版注册码:(适合最新版本) 推荐(尚未被封的 Realkey) FLASHFXPvACq2ssbvAAAAAC1W7cJKQTzmx77zmqJICvA7d3WnUtWNX ...
- VHS介绍
Java.JS HTTP流传输(VHS)介绍“我怎么才能让我的视频和Video.js一起玩?”“ 这是我们在使用Vio.js时最常见的问题之一.这是个好问题. 如果有人检查了Vo.js的拷贝,他们的内 ...
- 【转】chrome devtools protocol——Web 性能自动化
前言 在测试Web页面加载时间时,可能会是这样的: 打开chrome浏览器. 按F12打开开发者工具. 在浏览器上打开要测试的页面 查看开发者工具中Network面板的页面性能数据并记录 或者在开发者 ...
- POJ-2386.Lakecounting(DFS求连通块)
本题是一道连通块的入门题,用来练手,后续还会更新连通块的题目. 本题大意:一个n * m 的陆地上面有很多水洼,让你统计水洼的个数并输出. 本题思路:按照顺序遍历陆地,如果发现水洼就将它的八连块都进行 ...
- 154. Find Minimum in Rotated Sorted Array II (Array; Divide-and-Conquer)
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...
- Kylin Cube构建过程优化
原文地址:https://kylin.apache.org/docs16/howto/howto_optimize_build.html Kylin将一个cube的build过程分解为若干个子步骤,然 ...