简介
package org.springframework.format;public interface Formatter<T> extends Printer<T>, Parser<T> {}
- Formatter继承了两个接口,因此得到了两个需实现的方法,String print(T fieldValue, Locale locale)和parse(String clientValue, Locale locale)
 - print:用于将服务器的出参格式化,成一个String
 - parse:将入参进行解析成任意类型
使用例子
 
实现一个Formatter
public class MyFormatter implements Formatter<Date> {private String pattern;public MyFormatter(String pattern) {this.pattern = pattern;}@Overridepublic String print(Date date, Locale locale) {if (date == null) {return "";}return getDateFormat(locale).format(date);}@Overridepublic Date parse(String formatted, Locale locale) throws ParseException {if (formatted.length() == 0) {return null;}return getDateFormat(locale).parse(formatted);}protected DateFormat getDateFormat(Locale locale) {DateFormat dateFormat = new SimpleDateFormat(this.pattern, locale);dateFormat.setLenient(false);return dateFormat;}}
可以声明一个Annotation ```java @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) public @interface MyFormatAnno {
String pattern() default “yyyy-MM-dd HH:mm:ss”;
}
3. 实现一个AnnotationFormatterFactory<T>```java/*** @author GaoXi* @date 2022/1/25 20:51*/public class MyFormatAnnoFormatterFactory implements AnnotationFormatterFactory<MyFormatAnno> {@Overridepublic Set<Class<?>> getFieldTypes() {return new HashSet<>(Collections.singletonList(Date.class));}@Overridepublic Printer<?> getPrinter(MyFormatAnno annotation, Class<?> fieldType) {return new MyFormatter(annotation.pattern());}@Overridepublic Parser<?> getParser(MyFormatAnno annotation, Class<?> fieldType) {return new MyFormatter(annotation.pattern());}}
疑问点
- FormatterRegistry SPI
 - FormatterRegistrar SPI
 
SpringMVC中的配置
这个Formatter一定是和客户端交互时使用的。所以官方文档链接到SpringMVC章节讲解。我们在例子中写好的这个东西如何去用
@DateFormatter
- 这个Formatter注解是Spring自带的。
 - 对于接收参数有用(非Json的)
 - 
自定义的使用方式
 需要配置
@Configuration//@EnableWebMvc 一定不要加,除非你想完全重写配置public class WebConfig implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addFormatterForFieldAnnotation(new MyFormatAnnoFormatterFactory());}}
- 
为什么对返回值无效
因为返回JSON走的是Jackson的序列化机制,不走@DateTimeFomatter机制。所以无效。
 
