Spring中Converter和Formatter,都是用来做数据转换的。他们都是在Spring 3.0才出现的。之前使用的数据处理类是PropertyEditor。可是PropertyEditor存在的问题是他不是线程安全的,同时他只能处理String到其他类型的转换。其实应用中需要转换的地方还蛮常见的,比如日期类型转成指定格式再输出等。先来来看下这两个接口都有哪些方法:
Converter中只有一个方法convert
public interface Converter<S, T> {
/**
* Convert the source object of type {@code S} to target type {@code T}.
* @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
* @return the converted object, which must be an instance of {@code T} (potentially {@code null})
* @throws IllegalArgumentException if the source cannot be converted to the desired target type
*/
T convert(S source);
}
Formatter继承了Printer和Parser接口
public interface Formatter<T> extends Printer<T>, Parser<T> {
}
,Printer用来打印转换后的对象
public interface Printer<T> {
/**
* Print the object of type T for display.
* @param object the instance to print
* @param locale the current user locale
* @return the printed text string
*/
String print(T object, Locale locale);
}
,Parser用来从String类型转换为指定类型值
public interface Parser<T> {
/**
* Parse a text String to produce a T.
* @param text the text string
* @param locale the current user locale
* @return an instance of T
* @throws ParseException when a parse exception occurs in a java.text parsing library
* @throws IllegalArgumentException when a parse exception occurs
*/
T parse(String text, Locale locale) throws ParseException;
}
从方法上,可以看分出2个接口的一些区别:Converter可以从任意源类型,转换为任意目标类型。而Formatter则是从String类型转换为任务目标类型,有点类似PropertyEditor。可以感觉出Converter是Formater的超集,实际上在Spring中Formatter是被拆解成PrinterConverter和ParserConverter,然后再注册到ConverterRegistry,供后续使用。这块后面再写文章说明:)