当前位置:首页 > 技术知识 > 正文内容

Spring中字段格式化的使用详解_spring中字段格式化的使用详解是什么

maynowei6个月前 (09-06)技术知识55

环境: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实现。数字包提供了NumberStyleFormatterCurrencyStyleFormatterPercentStyleFormatter来格式化使用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

  1. getFieldTypes()返回可以使用注释的字段类型。
  2. getPrinter()返回一个Printer来打印带注释的字段的值。
  3. 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死信队列详解

相关文章

网络安全常用术语(网络安全常用术语介绍)

黑客帽子之分白帽白帽:亦称白帽黑客、白帽子黑客,是指那些专门研究或者从事网络、计算机技术防御的人,他们通常受雇于各大公司,是维护世界网络、计算机安全的主要力量。很多白帽还受雇于公司,对产品进行模拟黑客...

Linux C++实现多线程同步的四种方式(超级详细)

背景问题:在特定的应用场景下,多线程不进行同步会造成什么问题?通过多线程模拟多窗口售票为例:#include <iostream>#include<pthread.h>#inc...

一个快要被忘记的数据库开发岗位,但应该被尊重

数据库测试,似乎是被人遗忘的数据库职业,但依然是不错的选择。底下是我在某站找的招聘启事,就连蚂蚁金服都在积极寻找数据库测试人:要说我经历的项目,大大小小也有几十个,从 C/S, B/S, 再到 B/C...

Oracle数据库云服务系列新增前所未有的企业级功能

新推出的关键任务型功能包括:实现容错可用性和按需可扩展性的集群;零数据丢失灾难恢复;Oracle数据库Exadata云服务。甲骨文还宣布推出一项最新免费数据库云服务,数据库管理员和开发人员通过该服务可...

超详细的Oracle19c修改数据库用户名教程

概述由于开发很多视图指定了某个用户名,故需修改数据库用户名srmpro为srm。以下为操作过程..1、停止应用防止修改用户名密码后应用一直在发起错误连接,可事先查询哪个IP在连接数据库,然后断开对应连...

Oracle-架构、原理、进程(oracle进程结构)

详解:首先看张图:对于一个数据库系统来说,假设这个系统没有运行,我们所能看到的和这个数据库相关的无非就是几个基于操作系统的物理文件,这是从静态的角度来看,如果从动态的角度来看呢,也就是说这个数据库系统...