Infra 字段格式化

前一节 所述,core.convert 是一个通用的类型转换系统。 它提供了一个统一的 ConversionService API 以及一个强类型的 Converter SPI,用于实现从一种类型到另一种类型的转换逻辑。 Infra 容器使用此系统绑定 bean 属性值。 此外,Infra 表达式语言 (SpEL) 和 DataBinder 都使用此系统绑定字段值。 例如,当 SpEL 需要将 Short 强制转换为 Long 以完成 expression.setValue(Object bean, Object value) 尝试时, core.convert 系统执行该强制转换。

现在考虑典型客户端环境(例如 Web 或桌面应用程序)的类型转换要求。 在此类环境中,您通常从 String 转换以支持客户端回发过程,以及转换回 String 以支持视图渲染过程。 此外,您经常需要本地化 String 值。更通用的 core.convert Converter SPI 不直接解决此类格式化要求。 为了直接解决这些问题,Infra 提供了一个方便的 Formatter SPI,它为客户端环境提供了一个简单而强大的 PropertyEditor 实现替代方案。

通常,当您需要实现通用类型转换逻辑(例如,在 java.util.DateLong 之间进行转换)时,可以使用 Converter SPI。 当您在客户端环境(例如 Web 应用程序)中工作并且需要解析和打印本地化字段值时,可以使用 Formatter SPI。 ConversionService 为这两个 SPI 提供了统一的类型转换 API。

Formatter SPI

用于实现字段格式化逻辑的 Formatter SPI 简单且强类型化。 以下清单显示了 Formatter 接口定义:

package infra.format;

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

Formatter 扩展了 PrinterParser 构建块接口。 以下清单显示了这两个接口的定义:

public interface Printer<T> {

  String print(T fieldValue, Locale locale);
}
import java.text.ParseException;

public interface Parser<T> {

  T parse(String clientValue, Locale locale) throws ParseException;
}

要创建自己的 Formatter,请实现前面显示的 Formatter 接口。 将 T 参数化为您希望格式化的对象类型 — 例如,java.util.Date。 实现 print() 操作以打印 T 的实例以在客户端区域设置中显示。 实现 parse() 操作以从客户端区域设置返回的格式化表示形式解析 T 的实例。 如果解析尝试失败,您的 Formatter 应该抛出 ParseExceptionIllegalArgumentException。 请务必确保您的 Formatter 实现是线程安全的。

format 子包提供了几个 Formatter 实现以方便使用。 number 包提供 NumberStyleFormatterCurrencyStyleFormatterPercentStyleFormatter 以使用 java.text.NumberFormat 格式化 Number 对象。 datetime 包提供 DateFormatter 以使用 java.text.DateFormat 格式化 java.util.Date 对象。

以下 DateFormatter 是一个 Formatter 实现示例:

  • Java

package infra.format.datetime;

public final class DateFormatter implements Formatter<Date> {

  private String pattern;

  public DateFormatter(String pattern) {
    this.pattern = pattern;
  }

  public String print(Date date, Locale locale) {
    if (date == null) {
      return "";
    }
    return getDateFormat(locale).format(date);
  }

  public 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;
  }
}

Infra 团队欢迎社区驱动的 Formatter 贡献。请参阅 GitHub Issues 进行贡献。

注解驱动的格式化

字段格式化可以通过字段类型或注解进行配置。要将注解绑定到 Formatter,请实现 AnnotationFormatterFactory。 以下清单显示了 AnnotationFormatterFactory 接口的定义:

package infra.format;

public interface AnnotationFormatterFactory<A extends Annotation> {

  Set<Class<?>> getFieldTypes();

  Printer<?> getPrinter(A annotation, Class<?> fieldType);

  Parser<?> getParser(A annotation, Class<?> fieldType);
}

创建一个实现:

  1. A 参数化为您希望关联格式化逻辑的字段 annotationType — 例如 infra.format.annotation.DateTimeFormat

  2. getFieldTypes() 返回可以使用注解的字段类型。

  3. getPrinter() 返回一个 Printer 以打印带注解字段的值。

  4. getParser() 返回一个 Parser 以解析带注解字段的 clientValue

以下示例 AnnotationFormatterFactory 实现将 @NumberFormat 注解绑定到格式化程序,以允许指定数字样式或模式:

  • Java

public final class NumberFormatAnnotationFormatterFactory
    implements AnnotationFormatterFactory<NumberFormat> {

  private static final Set<Class<?>> FIELD_TYPES = Set.of(Short.class,
      Integer.class, Long.class, Float.class, Double.class,
      BigDecimal.class, BigInteger.class);

  public Set<Class<?>> getFieldTypes() {
    return FIELD_TYPES;
  }

  public Printer<Number> getPrinter(NumberFormat annotation, Class<?> fieldType) {
    return configureFormatterFrom(annotation, fieldType);
  }

  public Parser<Number> getParser(NumberFormat annotation, Class<?> fieldType) {
    return configureFormatterFrom(annotation, fieldType);
  }

  private Formatter<Number> configureFormatterFrom(NumberFormat annotation, Class<?> fieldType) {
    if (!annotation.pattern().isEmpty()) {
      return new NumberStyleFormatter(annotation.pattern());
    }
    // else
    return switch(annotation.style()) {
      case Style.PERCENT -> new PercentStyleFormatter();
      case Style.CURRENCY -> new CurrencyStyleFormatter();
      default -> new NumberStyleFormatter();
    };
  }
}

要触发格式化,您可以使用 @NumberFormat 注解字段,如下例所示:

  • Java

public class MyModel {

  @NumberFormat(style=Style.CURRENCY)
  private BigDecimal decimal;
}

格式注解 API

infra.format.annotation 包中存在一个可移植的格式注解 API。 您可以使用 @NumberFormat 格式化 Number 字段,例如 DoubleLong, 以及使用 @DateTimeFormat 格式化 java.util.Datejava.util.CalendarLong(用于毫秒时间戳)以及 JSR-310 java.time

以下示例使用 @DateTimeFormatjava.util.Date 格式化为 ISO 日期 (yyyy-MM-dd):

  • Java

public class MyModel {

  @DateTimeFormat(iso=ISO.DATE)
  private Date date;
}

FormatterRegistry SPI

FormatterRegistry 是用于注册格式化程序和转换器的 SPI。 FormattingConversionService 是适用于大多数环境的 FormatterRegistry 实现。 您可以以编程方式或声明方式将此变体配置为 Infra bean,例如使用 FormattingConversionServiceFactoryBean。 因为此实现也实现了 ConversionService,所以您可以直接配置它以与 Infra DataBinder 和 Infra 表达式语言 (SpEL) 一起使用。

以下清单显示了 FormatterRegistry SPI:

package infra.format;

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);
}

如前面的清单所示,您可以按字段类型或注解注册格式化程序。

FormatterRegistry SPI 允许您集中配置格式化规则,而不是在控制器之间重复此类配置。 例如,您可能希望强制所有日期字段以某种方式格式化,或者具有特定注解的字段以某种方式格式化。 使用共享的 FormatterRegistry,您可以定义一次这些规则,并且只要需要格式化就会应用这些规则。

FormatterRegistrar SPI

FormatterRegistrar 是一个用于通过 FormatterRegistry 注册格式化程序和转换器的 SPI。 以下清单显示了其接口定义:

package infra.format;

public interface FormatterRegistrar {

  void registerFormatters(FormatterRegistry registry);
}

当为给定的格式化类别(例如日期格式化)注册多个相关的转换器和格式化程序时,FormatterRegistrar 非常有用。 在声明性注册不足的情况下也很有用 — 例如,当格式化程序需要在与其自己的 <T> 不同的特定字段类型下建立索引时, 或者在注册 Printer/Parser 对时。下一节将提供有关转换器和格式化程序注册的更多信息。

在 Web MVC 中配置格式化

请参阅 Web MVC 章节中的 转换和格式化