在Web项目中,通常需要将数据转换为具有某种格式的字符串进行展示,因此Spring3引入了格式化转换器(Formatter SPI) 和格式化服务API(FormattingConversionService)从而支持这种需求。现在来看看格式转换器相关的接口定义:
- Printer接口:格式化显示接口,将T类型的对象根据Locale信息以某种格式进行打印显示(即返回字符串形式),源码如下图所示:
package org.springframework.format;
import java.util.Locale;
public interface Printer<T> {
//将Objct转成String
String print(T object, Locale locale);
}
- Parser接口:解析接口,根据Locale信息解析字符串到T类型的对象;
package org.springframework.format;
import java.text.ParseException;
import java.util.Locale;
public interface Parser<T> {
//根据text转成T对象
T parse(String text, Locale locale) throws ParseException;
}
从这两个接口定义中我们可以很清晰的看出定义了两个相反的接口。而下面的接口却同时继承了上面的两个接口。Formatter接口:格式化SPI接口,继承Printer和Parser接口,完成T类型对象的格式化和解析功能;源码如下:
package org.springframework.format;
public interface Formatter<T> extends Printer<T>, Parser<T> {
}
Formatter接口体系是如何融入到Converter体系的呢,从上面接口的定义我们可以认为Print接口是将任意类型换成String类型的converter,而Parser接口是将String类型转换成任意类型的converter。在Spring内部实现上也是这么做的,下面是ParserConverter的类定义,关键的信息有相应的注释,这个类定义在FormattingConversionService这个类中,代码如下图所示:


FormattingConversionService
FormattingConversionService这个类又是用来作什么的呢,我们先看这个类的继承结构,如下图所示:
从上图可以看出FormattingConversionService继承了ConversionService,自然就有ConversionService体系的一系列方法了。在FormattingConversionService内部会将Printer和Parser转成他内部实现的Converter。我们来看看源码是如何做的吧,源代码如下:

通过上面的分析能够很清晰的看出用的还是Spring Conversion的转换体系。
DateTimeFormat
有过Web开发经验的应该都用过@DateTimeFormat注解用于将特定格式的String转成Data类型吧。Spring为了支持注解类型的parse和print定义了AnnotationFormatterFactory接口以下是源码:





总结:
Formatter会转成Converter体系进行类型转换
网友评论