自定义转换器
当某些数据无法正常的通过自带的转换器从String类型转换到指定的类型的时候,需要自定义转换器:
可以通过实现Converter<TSource TTarget>接口,并重写TTarget convert(TSource t)方法来实现。
想要将自定义的转换器添加到SpringMVC需要配置ConversionServiceFactoryBean:
并且,配置annotation-driven标签的conversion-service属性:
Formatter
formatter的适用范围限定于web层,只能将String类型的数据转换为其他类型数据,也就是说,其TSource只能是String,限制太大。
需要自定义Formatter,需要实现Formatter<T>接口:
重写parse和print方法:
使用示例:
当有Formatter需要注册到SpringMVC时,我们需要使用FormattingConversionServiceFactoryBean替换ConversionServiceFactoryBean:
想要注册converters可以使用<property name="converters">注册
并指定annotation-driven:
也可以使用注册类代替:
但也需要在xml中指定注册类: