Spring中字段格式化的使用详解
环境:Spring5.3.12.RELEASE
Spring提供的一个core.convert包是一个通用类型转换系统。它提供了统一的ConversionService API和强类型的Converter SPI,用于实现从一种类型到另一种类型的转换逻辑。Spring容器使用这个系统绑定bean属性值。此外,Spring Expression Language (SpEL)和DataBinder都使用这个系统来绑定字段值。例如,当SpEL需要将Short强制转换为Long来完成表达式时。setValue(对象bean,对象值)尝试,核心。转换系统执行强制转换。
现在考虑典型客户端环境(例如web或桌面应用程序)的类型转换需求。在这种环境中,通常从String转换为支持客户端回发过程,并返回String以支持视图呈现过程。此外,你经常需要本地化String值。更一般的core.convert Converter SPI不能直接解决这些格式要求。为了直接解决这些问题,Spring 3引入了一个方便的Formatter SPI,它为客户端环境提供了PropertyEditor实现的一个简单而健壮的替代方案。
通常,当你需要实现通用类型转换逻辑时,你可以使用Converter SPI,例如,用于java.util.Date和Long之间的转换。当你在客户端环境(例如web应用程序)中工作并需要解析和打印本地化的字段值时,你可以使用Formatter SPI。ConversionService为这两个spi提供了统一的类型转换API。
1 Formatter SPI
实现字段格式化逻辑的Formatter SPI是简单且强类型的。下面的清单显示了Formatter接口定义:
package org.springframework.format;
public interface Formatter<T> extends Printer<T>, Parser<T> {
}Formatter继承自Printer和Parser接口
@FunctionalInterface
public interface Printer<T> {
  String print(T object, Locale locale);
}
@FunctionalInterface
public interface Parser<T> {
  T parse(String text, Locale locale) throws ParseException;
}默认情况下Spring容器提供了几个Formatter实现。数字包提供了NumberStyleFormatter、CurrencyStyleFormatter和PercentStyleFormatter来格式化使用java.text.NumberFormat的number对象。datetime包提供了一个DateFormatter来用java.text.DateFormat格式化 java.util.Date对象。
自定义Formatter
public class StringToNumberFormatter implements Formatter<Number> {
  @Override
  public String print(Number object, Locale locale) {
    return "结果是:" + object.toString();
  }
  @Override
  public Number parse(String text, Locale locale) throws ParseException {
    return NumberFormat.getInstance().parse(text);
  }
}如何使用?我们可以通过FormattingConversionService 转换服务进行添加自定义的格式化类。
FormattingConversionService fcs = new FormattingConversionService();
// 默认如果不添加自定义的格式化类,那么程序运行将会报错
fcs.addFormatterForFieldType(Number.class, new StringToNumberFormatter());
Number number = fcs.convert("100.5", Number.class);
System.out.println(number);查看源码
public class FormattingConversionService extends GenericConversionService implements FormatterRegistry, EmbeddedValueResolverAware {
  public void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter) {
    addConverter(new PrinterConverter(fieldType, formatter, this));
    addConverter(new ParserConverter(fieldType, formatter, this));
  }
  private static class PrinterConverter implements GenericConverter {}
  private static class ParserConverter implements GenericConverter {}
}
public class GenericConversionService implements ConfigurableConversionService {
  private final Converters converters = new Converters();
  public void addConverter(GenericConverter converter) {
    this.converters.add(converter);
  }
}Formatter最后还是被适配成GenericConverter(类型转换接口)。
2 基于注解的格式化
字段格式化可以通过字段类型或注释进行配置。要将注释绑定到Formatter,请实现 AnnotationFormatterFactory
public interface AnnotationFormatterFactory<A extends Annotation> {
  Set<Class<?>> getFieldTypes();
  Printer<?> getPrinter(A annotation, Class<?> fieldType);
  Parser<?> getParser(A annotation, Class<?> fieldType);
}类及其方法说明:
参数化A为字段注解类型,你希望将该字段与格式化逻辑关联,例如org.springframework.format.annotation.DateTimeFormat。
- getFieldTypes()返回可以使用注释的字段类型。
 - getPrinter()返回一个Printer来打印带注释的字段的值。
 - getParser()返回一个Parser来解析带注释字段的clientValue。
 
自定义注解解析器
public class StringToDateFormatter implements AnnotationFormatterFactory<DateFormatter> {
  @Override
  public Set<Class<?>> getFieldTypes() {
    return new HashSet<Class<?>>(Arrays.asList(Date.class));
  }
  @Override
  public Printer<?> getPrinter(DateFormatter annotation, Class<?> fieldType) {
    return getFormatter(annotation, fieldType);
  }
  @Override
  public Parser<?> getParser(DateFormatter annotation, Class<?> fieldType) {
    return getFormatter(annotation, fieldType);
  }
  private StringFormatter getFormatter(DateFormatter annotation, Class<?> fieldType) {
    String pattern = annotation.value();
    return new StringFormatter(pattern);
  }
  class StringFormatter implements Formatter<Date> {
    private String pattern;
    public StringFormatter(String pattern) {
      this.pattern = pattern;
    }
    @Override
    public String print(Date date, Locale locale) {
      return DateTimeFormatter.ofPattern(pattern, locale).format(date.toInstant());
    }
    @Override
    public Date parse(String text, Locale locale) throws ParseException {
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, locale);
      return Date.from(LocalDate.parse(text, formatter).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }
  }
}注册及使用
public class Main {
  @DateFormatter("yyyy年MM月dd日")
  private Date date;
  public static void main(String[] args) throws Exception {
    FormattingConversionService fcs = new FormattingConversionService();
    fcs.addFormatterForFieldAnnotation(new StringToDateFormatter());
    Main main = new Main();
    Field field = main.getClass().getDeclaredField("date");
    TypeDescriptor targetType = new TypeDescriptor(field);
    Object result = fcs.convert("2022年01月21日", targetType);
    System.out.println(result);
    field.setAccessible(true);
    field.set(main, result);
    System.out.println(main.date);
  }
}3 FormatterRegistry
FormatterRegistry是用于注册格式化程序和转换器的SPI。FormattingConversionService是FormatterRegistry的一个实现,适用于大多数环境。可以通过编程或声明的方式将该变体配置为Spring bean,例如使用FormattingConversionServiceFactoryBean。因为这个实现还实现了ConversionService,所以您可以直接配置它,以便与Spring的DataBinder和Spring表达式语言(SpEL)一起使用。
public interface FormatterRegistry extends ConverterRegistry {
  void addPrinter(Printer<?> printer);
  void addParser(Parser<?> parser);
  void addFormatter(Formatter<?> formatter);
  void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter);
  void addFormatterForFieldType(Class<?> fieldType, Printer<?> printer, Parser<?> parser);
  void addFormatterForFieldAnnotation(AnnotationFormatterFactory<? extends Annotation> annotationFormatterFactory);
}4 SpringMVC中配置类型转换
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
  @Override
  public void addFormatters(FormatterRegistry registry) {
    // ...
  }
}SpringBoot中有如下的默认类型转换器
public class WebMvcAutoConfiguration {
  public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
    @Bean
    @Override
    public FormattingConversionService mvcConversionService() {
      Format format = this.mvcProperties.getFormat();
      WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime()));
      addFormatters(conversionService);
      return conversionService;
    }    
  }
}完毕!!!
Spring MVC 异步请求方式 
Spring容器这些扩展点你都清楚了吗? 
Springboot整合openfeign使用详解
 Spring 引介增强IntroductionAdvisor使用 
Spring中自定义数据类型转换详解 
SpringBoot开发自己的Starter 
SpringBoot项目中Redis之管道技术 
Springboot中Redis事务的使用及Lua脚本
 Springboot整合RabbitMQ死信队列详解 
相关文章
- Spring Boot中对接Twilio以实现发送验证码和验证短信码
 - Spring Boot 3.5:这次更新让你连配置都不用写了,惊不惊喜?
 - Spring Boot+Pinot实战:毫秒级实时竞价系统构建
 - SpringBoot敏感配置项加密与解密实战
 - SpringBoot 注解最全详解,建议收藏!
 - Spring Boot 常用注解大全:从入门到进阶
 - SpringBoot启动之谜:@SpringBootApplication如何让配置化繁为简
 - Springboot集成Kafka原理_spring集成kafka的原理
 - Spring Boot中@Data注解的深度解析与实战应用
 - 大佬用1000字就把SpringBoot的配置文件讲的明明白白!
 
