在如Web /客户端项目中,通常需要将数据转换为具有某种格式的字符串进行展示,因此上节我们学习的数据类型转换系统核心作用不是完成这个需求,因此Spring3引入了格式化转换器(Formatter SPI) 和格式化服务API(FormattingConversionService)从而支持这种需求。在Spring中它和PropertyEditor功能类似,可以替代PropertyEditor来进行对象的解析和格式化,而且支持细粒度的字段级别的格式化/解析。
Formatter SPI核心是完成解析和格式化转换逻辑,在如Web应用/客户端项目中,需要解析、打印/展示本地化的对象值时使用,如根据Locale信息将java.util.Date—->java.lang.String打印/展示、java.lang.String—->java.util.Date等。
架构
一共有如下两组四个接口:
Printer接口
Printer接口:格式化显示接口,将T类型的对象根据Locale信息以某种格式进行打印显示(即返回字符串形式);
package org.springframework.format;
public interface Printer<T> {
String print(T object, Locale locale);
}
Parser接口
Parser接口:解析接口,根据Locale信息解析字符串到T类型的对象;
package org.springframework.format;
public interface Parser<T> {
T parse(String text, Locale locale) throws ParseException;
}
解析失败可以抛出java.text.ParseException或IllegalArgumentException异常即可。
Formatter接口
格式化SPI接口,继承Printer和Parser接口,完成T类型对象的格式化和解析功能;
package org.springframework.format;
public interface Formatter<T> extends Printer<T>, Parser<T> {
}
AnnotationFormatterFactory接口
注解驱动的字段格式化工厂,用于创建带注解的对象字段的Printer和Parser,即用于格式化和解析带注解的对象字段.
package org.springframework.format;
public interface AnnotationFormatterFactory<A extends Annotation> {
//①可以识别的注解类型
Set<Class<?>> getFieldTypes();//②可以被A注解类型注解的字段类型集合
Printer<?> getPrinter(A annotation, Class<?> fieldType);//③根据A注解类型和fieldType类型获取Printer
Parser<?> getParser(A annotation, Class<?> fieldType);//④根据A注解类型和fieldType类型获取Parser
}
返回用于格式化和解析被A注解类型注解的字段值的Printer和Parser。如JodaDateTimeFormatAnnotationFormatterFactory可以为带有@DateTimeFormat注解的java.util.Date字段类型创建相应的Printer和Parser进行格式化和解析
格式化转换器注册器、格式化服务
提供类型转换器注册支持,运行时类型转换API支持。
一个有如下两种接口:
FormatterRegistry
FormatterRegistry:格式化转换器注册器,用于注册格式化转换器(Formatter、Printer和Parser、AnnotationFormatterFactory);
package org.springframework.format;
public interface FormatterRegistry extends ConverterRegistry {
//①添加格式化转换器&