Spring官网阅读(十五)Spring中的格式化(Formatter)

灰太狼 2023-07-20 10:41 118阅读 0赞

文章目录

  • Formatter
    • 接口定义
    • 继承树
  • 注解驱动的格式化
    • AnnotationFormatterFactory
  • FormatterRegistry
    • 接口定义
    • UML类图
      • FormattingConversionService
      • DefaultFormattingConversionService
      • FormatterRegistrar
  • 配置SpringMVC中的格式化器
    • 配置实现的原理
  • 总结

在上篇文章中,我们已经学习过了Spring中的类型转换机制。现在我们考虑这样一个需求:在我们web应用中,我们经常需要将前端传入的字符串类型的数据转换成指定格式或者指定数据类型来满足我们调用需求,同样的,后端开发也需要将返回数据调整成指定格式或者指定类型返回到前端页面。这种情况下,Converter已经没法直接支撑我们的需求了。这个时候,格式化的作用就很明显了,这篇文章我们就来介绍Spring中格式化的一套体系。本文主要涉及官网中的3.53.6小结

Formatter

接口定义

  1. public interface Formatter<T> extends Printer<T>, Parser<T> {
  2. }

可以看到,本身这个接口没有定义任何方法,只是聚合了另外两个接口的功能

  • Printer

    // 将T类型的数据根据Locale信息打印成指定格式,即返回字符串的格式
    public interface Printer {

    1. String print(T fieldValue, Locale locale);

    }

  • Parser

    public interface Parser {

    1. // 将指定的字符串根据Locale信息转换成指定的T类型数据
    2. T parse(String clientValue, Locale locale) throws ParseException;

    }

从上面可以看出,这个两个接口维护了两个功能相反的方法,分别完成对String类型数据的解析以及格式化。

继承树

在这里插入图片描述

可以发现整个继承关系并不复杂,甚至可以说非常简单。只有一个抽象子类,AbstractNumberFormatter,这个类抽象了对数字进行格式化时的一些方法,它有三个子类,分别处理不同的数字类型,包括货币百分数,正常数字。其余的子类都是直接实现了Formatter接口。其中我们比较熟悉的可能就是DateFormatter

使用如下:

  1. public class Main {
  2. public static void main(String[] args) throws Exception {
  3. DateFormatter dateFormatter = new DateFormatter();
  4. dateFormatter.setIso(DateTimeFormat.ISO.DATE);
  5. System.out.println(dateFormatter.print(new Date(), Locale.CHINA));
  6. System.out.println(dateFormatter.parse("2020-03-26", Locale.CHINA));
  7. // 程序打印:
  8. // 2020-03-26
  9. // Thu Mar 26 08:00:00 CST 2020
  10. }
  11. }

注解驱动的格式化

我们在配置格式化时,除了根据类型进行格式外(比如常见的根据Date类型进行格式化),还可以根据注解来进行格式化,最常见的注解就是org.springframework.format.annotation.DateTimeFormat。除此之外还有NumberFormat,它们都在format包下。

在这里插入图片描述

为了将一个注解绑定到指定的格式化器上,我们需要借助到一个接口AnnotationFormatterFactory

AnnotationFormatterFactory

  1. public interface AnnotationFormatterFactory<A extends Annotation> {
  2. // 可能被添加注解的字段的类型
  3. Set<Class<?>> getFieldTypes();
  4. // 根据注解及字段类型获取一个格式化器
  5. Printer<?> getPrinter(A annotation, Class<?> fieldType);
  6. // 根据注解及字段类型获取一个解析器
  7. Parser<?> getParser(A annotation, Class<?> fieldType);
  8. }

以Spring内置的一个DateTimeFormatAnnotationFormatterFactory来说,这个类实现的功能就是将DateTimeFormat注解绑定到指定的格式化器,源码如下:

  1. public class DateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
  2. implements AnnotationFormatterFactory<DateTimeFormat> {
  3. private static final Set<Class<?>> FIELD_TYPES;
  4. // 只有在这些类型下加这个注解才会进行格式化
  5. static {
  6. Set<Class<?>> fieldTypes = new HashSet<>(4);
  7. fieldTypes.add(Date.class);
  8. fieldTypes.add(Calendar.class);
  9. fieldTypes.add(Long.class);
  10. FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
  11. }
  12. @Override
  13. public Set<Class<?>> getFieldTypes() {
  14. return FIELD_TYPES;
  15. }
  16. @Override
  17. public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) {
  18. return getFormatter(annotation, fieldType);
  19. }
  20. @Override
  21. public Parser<?> getParser(DateTimeFormat annotation, Class<?> fieldType) {
  22. return getFormatter(annotation, fieldType);
  23. }
  24. protected Formatter<Date> getFormatter(DateTimeFormat annotation, Class<?> fieldType) { // 通过这个DateFormatter来完成格式化
  25. DateFormatter formatter = new DateFormatter();
  26. String style = resolveEmbeddedValue(annotation.style());
  27. if (StringUtils.hasLength(style)) {
  28. formatter.setStylePattern(style);
  29. }
  30. formatter.setIso(annotation.iso());
  31. String pattern = resolveEmbeddedValue(annotation.pattern());
  32. if (StringUtils.hasLength(pattern)) {
  33. formatter.setPattern(pattern);
  34. }
  35. return formatter;
  36. }
  37. }

使用@DateTimeFormat,我们只需要在字段上添加即可

  1. public class MyModel {
  2. @DateTimeFormat(iso=ISO.DATE)
  3. private Date date;
  4. }

关于日期的格式化,Spring还提供了一个类似的AnnotationFormatterFactory,专门用于处理java8中的日期格式,如下

  1. public class Jsr310DateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
  2. implements AnnotationFormatterFactory<DateTimeFormat> {
  3. private static final Set<Class<?>> FIELD_TYPES;
  4. static {
  5. // 这里添加了对Java8日期的支持
  6. Set<Class<?>> fieldTypes = new HashSet<>(8);
  7. fieldTypes.add(LocalDate.class);
  8. fieldTypes.add(LocalTime.class);
  9. fieldTypes.add(LocalDateTime.class);
  10. fieldTypes.add(ZonedDateTime.class);
  11. fieldTypes.add(OffsetDateTime.class);
  12. fieldTypes.add(OffsetTime.class);
  13. FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
  14. }
  15. ........

学习到现在,对Spring的脾气大家应该都有所了解,上面这些都是定义了具体的功能实现,它们必定会有一个管理者,一个Registry,用来注册这些格式化器

FormatterRegistry

接口定义

  1. // 继承了ConverterRegistry,所以它同时还是一个Converter注册器
  2. public interface FormatterRegistry extends ConverterRegistry {
  3. // 一系列添加格式化器的方法
  4. void addFormatterForFieldType(Class<?> fieldType, Printer<?> printer, Parser<?> parser);
  5. void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter);
  6. void addFormatterForFieldType(Formatter<?> formatter);
  7. void addFormatterForAnnotation(AnnotationFormatterFactory<?, ?> factory);
  8. }

UML类图

在这里插入图片描述

我们可以发现FormatterRegistry默认只有两个实现类

FormattingConversionService

  1. // 继承了GenericConversionService ,所以它能对Converter进行一系列的操作
  2. // 实现了接口FormatterRegistry,所以它也可以注册格式化器了
  3. // 实现了EmbeddedValueResolverAware,所以它还能有非常强大的功能:处理占位符
  4. public class FormattingConversionService extends GenericConversionService implements FormatterRegistry, EmbeddedValueResolverAware {
  5. // ....
  6. // 最终也是交给addFormatterForFieldType去做的
  7. // getFieldType:它会拿到泛型类型。并且支持DecoratingProxy
  8. @Override
  9. public void addFormatter(Formatter<?> formatter) {
  10. addFormatterForFieldType(getFieldType(formatter), formatter);
  11. }
  12. // 存储都是分开存储的 读写分离
  13. // PrinterConverter和ParserConverter都是一个GenericConverter 采用内部类实现的
  14. // 注意:他们的ConvertiblePair必有一个类型是String.class
  15. // Locale一般都可以这么获取:LocaleContextHolder.getLocale()
  16. // 在进行printer之前,会先判断是否能进行类型转换,如果能进行类型转换会先进行类型转换,之后再格式化
  17. // 在parse之后,会判断是否还需要进行类型转换,如果需要类型转换会先进行类型转换
  18. @Override
  19. public void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter) {
  20. addConverter(new PrinterConverter(fieldType, formatter, this));
  21. addConverter(new ParserConverter(fieldType, formatter, this));
  22. }
  23. // 哪怕你是一个AnnotationFormatterFactory,最终也是被适配成了GenericConverter(ConditionalGenericConverter)
  24. @Override
  25. public void addFormatterForFieldAnnotation(AnnotationFormatterFactory<? extends Annotation> annotationFormatterFactory) {
  26. Class<? extends Annotation> annotationType = getAnnotationType(annotationFormatterFactory);
  27. // 若你自定义的实现了EmbeddedValueResolverAware接口,还可以使用占位符哟
  28. // AnnotationFormatterFactory是下面的重点内容
  29. if (this.embeddedValueResolver != null && annotationFormatterFactory instanceof EmbeddedValueResolverAware) {
  30. ((EmbeddedValueResolverAware) annotationFormatterFactory).setEmbeddedValueResolver(this.embeddedValueResolver);
  31. }
  32. // 对每一种字段的type 都注册一个AnnotationPrinterConverter去处理
  33. // AnnotationPrinterConverter是一个ConditionalGenericConverter
  34. // matches方法为:sourceType.hasAnnotation(this.annotationType);
  35. // 这个判断是呼应的:因为annotationFormatterFactory只会作用在指定的字段类型上的,不符合类型条件的不用添加
  36. Set<Class<?>> fieldTypes = annotationFormatterFactory.getFieldTypes();
  37. for (Class<?> fieldType : fieldTypes) {
  38. addConverter(new AnnotationPrinterConverter(annotationType, annotationFormatterFactory, fieldType));
  39. addConverter(new AnnotationParserConverter(annotationType, annotationFormatterFactory, fieldType));
  40. }
  41. }
  42. // .......
  43. // 持有的一个内部类
  44. private static class PrinterConverter implements GenericConverter {
  45. private final Class<?> fieldType;
  46. private final TypeDescriptor printerObjectType;
  47. @SuppressWarnings("rawtypes")
  48. private final Printer printer;
  49. // 最终也是通过conversionService完成类型转换
  50. private final ConversionService conversionService;
  51. public PrinterConverter(Class<?> fieldType, Printer<?> printer, ConversionService conversionService) {
  52. this.fieldType = fieldType;
  53. this.printerObjectType =
  54. // 会通过解析Printer中的泛型获取具体类型,主要是为了判断是否需要进行类型转换
  55. TypeDescriptor.valueOf(resolvePrinterObjectType(printer));
  56. this.printer = printer;
  57. this.conversionService = conversionService;
  58. }
  59. // ......
  60. }

DefaultFormattingConversionService

类比我们上篇文中介绍的GenericConversionServiceDefaultConversionService,它相比于FormattingConversionService而言,提供了大量的默认的格式化器,源码如下:

  1. public class DefaultFormattingConversionService extends FormattingConversionService {
  2. private static final boolean jsr354Present;
  3. private static final boolean jodaTimePresent;
  4. static {
  5. ClassLoader classLoader = DefaultFormattingConversionService.class.getClassLoader();
  6. // 判断是否导入了jsr354相关的包
  7. jsr354Present = ClassUtils.isPresent("javax.money.MonetaryAmount", classLoader);
  8. // 判断是否导入了joda
  9. jodaTimePresent = ClassUtils.isPresent("org.joda.time.LocalDate", classLoader);
  10. }
  11. // 会注册很多默认的格式化器
  12. public DefaultFormattingConversionService() {
  13. this(null, true);
  14. }
  15. public DefaultFormattingConversionService(boolean registerDefaultFormatters) {
  16. this(null, registerDefaultFormatters);
  17. }
  18. public DefaultFormattingConversionService(
  19. @Nullable StringValueResolver embeddedValueResolver, boolean registerDefaultFormatters) {
  20. if (embeddedValueResolver != null) {
  21. setEmbeddedValueResolver(embeddedValueResolver);
  22. }
  23. DefaultConversionService.addDefaultConverters(this);
  24. if (registerDefaultFormatters) {
  25. addDefaultFormatters(this);
  26. }
  27. }
  28. public static void addDefaultFormatters(FormatterRegistry formatterRegistry) {
  29. // 添加针对@NumberFormat的格式化器
  30. formatterRegistry.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
  31. // 针对货币的格式化器
  32. if (jsr354Present) {
  33. formatterRegistry.addFormatter(new CurrencyUnitFormatter());
  34. formatterRegistry.addFormatter(new MonetaryAmountFormatter());
  35. formatterRegistry.addFormatterForFieldAnnotation(new Jsr354NumberFormatAnnotationFormatterFactory());
  36. }
  37. new DateTimeFormatterRegistrar().registerFormatters(formatterRegistry);
  38. // 如没有导入joda的包,那就默认使用Date
  39. if (jodaTimePresent) {
  40. // 针对Joda
  41. new JodaTimeFormatterRegistrar().registerFormatters(formatterRegistry);
  42. }
  43. else {
  44. // 没有joda的包,是否Date
  45. new DateFormatterRegistrar().registerFormatters(formatterRegistry);
  46. }
  47. }
  48. }

FormatterRegistrar

在上面DefaultFormattingConversionService的源码中,有这么几行:

  1. new JodaTimeFormatterRegistrar().registerFormatters(formatterRegistry);
  2. new DateFormatterRegistrar().registerFormatters(formatterRegistry);

其中的JodaTimeFormatterRegistrarDateFormatterRegistrar就是FormatterRegistrar。那么这个接口有什么用呢?我们先来看看它的接口定义:

  1. public interface FormatterRegistrar {
  2. // 最终也是调用FormatterRegistry来完成注册
  3. void registerFormatters(FormatterRegistry registry);
  4. }

我们思考一个问题,为什么已经有了FormatterRegistry,Spring还要开发一个FormatterRegistrar呢?直接使用FormatterRegistry完成注册不好吗?

以这句代码为例:new JodaTimeFormatterRegistrar().registerFormatters(formatterRegistry),这段代码是将joda包下所有的默认的转换器已经注册器都注册到formatterRegistry中。

我们可以发现FormatterRegistrar相当于对格式化器及转换器进行了分组,我们调用它的registerFormatters方法,相当于将这一组格式化器直接添加到指定的formatterRegistry中。这样做的好处在于,如果我们对同一个类型的数据有两组不同的格式化策略,例如就以上面的日期为例,我们既有可能采用joda的策略进行格式化,也有可能采用Date的策略进行格式化,通过分组的方式,我们可以更见方便的在确认好策略后将需要的格式化器添加到容器中。

配置SpringMVC中的格式化器

  1. @Configuration
  2. @EnableWebMvc
  3. public class WebConfig implements WebMvcConfigurer {
  4. @Override
  5. public void addFormatters(FormatterRegistry registry) {
  6. // 调用registry.addFormatter添加格式化器即可
  7. }
  8. }

配置实现的原理

  1. @EnableWebMvc注解上导入了一个DelegatingWebMvcConfiguration

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Documented
    @Import(DelegatingWebMvcConfiguration.class)
    public @interface EnableWebMvc {
    }

  2. DelegatingWebMvcConfiguration

    // 继承了WebMvcConfigurationSupport
    @Configuration
    public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

    1. private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
    2. // 这个方法会注入所有的WebMvcConfigurer,包括我们的WebConfig
    3. @Autowired(required = false)
    4. public void setConfigurers(List<WebMvcConfigurer> configurers) {
    5. if (!CollectionUtils.isEmpty(configurers)) {
    6. this.configurers.addWebMvcConfigurers(configurers);
    7. }
    8. }
    9. //.....,省略无关代码
    10. // 复写了父类WebMvcConfigurationSupport的方法
    11. // 调用我们配置的configurer的addFormatters方法
    12. @Override
    13. protected void addFormatters(FormatterRegistry registry) {
    14. this.configurers.addFormatters(registry);
    15. }

    //…..,省略无关代码
    }

3.WebMvcConfigurationSupport

  1. public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {
  2. // 这就是真相,这里会创建一个FormattingConversionService,并且是一个DefaultFormattingConversionService,然后调用addFormatters方法
  3. @Bean
  4. public FormattingConversionService mvcConversionService() {
  5. FormattingConversionService conversionService = new DefaultFormattingConversionService();
  6. addFormatters(conversionService);
  7. return conversionService;
  8. }
  9. protected void addFormatters(FormatterRegistry registry) {
  10. }
  11. }

总结

Spring中的格式化到此就结束了,总结画图如下:

在这里插入图片描述
扫描下方二维码,关注我的公众号,更多精彩文章在等您!~~

公众号

发表评论

表情:
评论列表 (有 0 条评论,118人围观)

还没有评论,来说两句吧...

相关阅读