广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring中字段格式化的使用小结
  • 779
分享到

Spring中字段格式化的使用小结

2024-04-02 19:04:59 779人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录1、FORMatter SPI2、基于注解的格式化3、FormatterReGIStry4、springMVC中配置类型转换spring提供的一个core.convert包&nb

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中字段格式化的使用详解的文章就介绍到这了,更多相关Spring字段格式化内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring中字段格式化的使用小结

本文链接: https://www.lsjlt.com/news/152650.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作