3.8 类型转换原理与设置
Spring为我们提供了ConversionService
接口用来做类型转换,它是Spring类型转换系统的入口。像我们注册的Formatter
的FormattingConversionService
类就是它的实现类。
FormattingConversionService
支持注册Formatter
、Converter
和AnnotationFormatterFactory
,它属于配置初始化数据绑定的一部分。
3.8.1 Formatter
Formatter
用于格式化(id|name|age
)对象类型(如Person
)。我们在前面已经演示了自定义的Format,这里就不再演示了,在AnnotationFormatterFactory
中我们将会使用大量的Formatter
。
3.8.2 Converter
或ConverterFactory
3.8.2.1 常用的Converter
或ConverterFactory
将源对象类型S
转换成目标对象类型T
,这个是Sping和Spring MVC对象之间类型转换的重要功能,若外部的对象类型是字符串"1",Spring MVC也能将它正确的转换成对应的数字类型。
我们的控制器做如下的检验:
@GetMapping("/{id}/convert")
public Map<String, Object> convert(@PathVariable Long id,
@RequestParam Boolean testBool,
@RequestBody Person person){
Map<String, Object> map = new HashMap<>();
map.put(