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

目录
  • 1、Formatter SPI
  • 2、基于注解的格式化
  • 3、FormatterRegistry
  • 4、SpringMVC中配置类型转换

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字段格式化内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Spring MVC通过添加自定义注解格式化数据的方法

    springmvc 自定义注解 以及自定义注解的解析 一.自定义注解名字 @Target({ElementType.TYPE, ElementType.METHOD}) //类名或方法上 @Retention(RetentionPolicy.RUNTIME)//运行时 @component//自定义多个注解,且在一个类中添加两个或以上的,只需要加一个 否则会实例化多次. public @interface SocketMapping { String value() default ""

  • Spring Boot LocalDateTime格式化处理的示例详解

    JDK8的新特性中Time API,其包括Clock.Duration.Instant.LocalDate.LocalTime.LocalDateTime.ZonedDateTime,在这里就不一一介绍了,相信很多人都会使用其代替Date及Calendar来处理日期时间,下面介绍Spring Boot处理LocalDateTime格式. Controller接收LocalDateTime参数 在Spring中,接收LocalDateTime日期时间数据时,只需要使用@DateTimeFormat

  • spring mvc4的日期/数字格式化、枚举转换示例

    日期.数字格式化显示,是web开发中的常见需求,spring mvc采用XXXFormatter来处理,先看一个最基本的单元测试: package com.cnblogs.yjmyzz.test; import java.math.BigDecimal; import java.util.Date; import java.util.Locale; import org.junit.Test; import org.springframework.context.i18n.LocaleConte

  • 关于Springboot日期时间格式化处理方式总结

    项目中使用LocalDateTime系列作为DTO中时间的数据类型,但是SpringMVC收到参数后总报错,为了配置全局时间类型转换,尝试了如下处理方式. 注:本文基于Springboot2.x测试,如果无法生效可能是spring版本较低导致的.PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam.PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数是使用ModelAttributeMethodProcessor进行处理,而

  • springboot json时间格式化处理的方法

    application.properties中加入如下代码 springboot 默认使用 jackson 解析 json spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 如果个别实体需要使用其他格式的 pattern,在实体上加入注解即可 import org.springframework.format.annotation.DateTimeFormat; import com.fas

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

    目录 1.Formatter SPI 2.基于注解的格式化 3.FormatterRegistry 4.SpringMVC中配置类型转换 Spring提供的一个core.convert包 是一个通用类型转换系统.它提供了统一的 ConversionService   API和强类型的Converter SPI,用于实现从一种类型到另一种类型的转换逻辑.Spring容器使用这个系统绑定bean属性值.此外,Spring Expression Language (SpEL)和DataBinder都使

  • Spring中集成Groovy的四种方式(小结)

    groovy是一种动态脚本语言,适用于一些可变.和规则配置性的需求,目前Spring提供ScriptSource接口,支持两种类型,一种是 ResourceScriptSource,另一种是 StaticScriptSource,但是有的场景我们需要把groovy代码放进DB中,所以我们需要扩展这个. ResourceScriptSource:在 resources 下面写groovy类 StaticScriptSource:把groovy类代码放进XML里 DatabaseScriptSour

  • 你知道Spring中为何不建议使用字段注入吗

    在使用Idea中通过注解注入字段时是否遇见过这样一个提示: Field injection is not recommended(不推荐使用字段注入) 一. 什么是字段注入,Spring中依赖注入的方式有哪些? 在Spring中依赖注入有三大类:字段注入.构造器注入.Setter方法注入. 字段注入是将Bean作为字段注入到类中,也是最方便,用的最多的注入方式. 二. 官方为什么不推荐使用字段注入 首先来看字段注入 @RestController public class TestHandleC

  • spring中12种@Transactional的失效场景(小结)

    目录 一.失效场景集一:代理不生效 二.失效场景集二:框架或底层不支持的功能 三.失效场景集三:错误使用@Transactional 四.总结 数据库事务是后端开发中不可缺少的一块知识点.Spring为了更好的支撑我们进行数据库操作,在框架中支持了两种事务管理的方式: 编程式事务声明式事务 日常我们进行业务开发时,基本上使用的都是声明式事务,即为使用@Transactional注解的方式. 常规使用时,Spring能帮我们很好的实现数据库的ACID (这里需要注意哦,Spring只是进行了编程上

  • 浅谈Spring中如何使用设计模式

    关于设计模式,如果使用得当,将会使我们的代码更加简洁,并且更具扩展性.本文主要讲解Spring中如何使用策略模式,工厂方法模式以及Builder模式. 1. 策略模式 关于策略模式的使用方式,在Spring中其实比较简单,从本质上讲,策略模式就是一个接口下有多个实现类,而每种实现类会处理某一种情况.我们以发奖励为例进行讲解,比如我们在抽奖系统中,有多种奖励方式可供选择,比如积分,虚拟币和现金等.在存储时,我们必然会使用一个类似于type的字段用于表征这几种发放奖励的,那么这里我们就可以使用多态的

  • SpringBoot中时间格式化的五种方法汇总

    目录 前言 时间问题演示 1.前端时间格式化 JS 版时间格式化 2.SimpleDateFormat格式化 3.DateTimeFormatter格式化 4.全局时间格式化 实现原理分析 5.部分时间格式化 总结 参考 & 鸣谢 前言 在我们日常工作中,时间格式化是一件经常遇到的事儿,所以本文我们就来盘点一下 Spring Boot 中时间格式化的几种方法. 时间问题演示 为了方便演示,我写了一个简单 Spring Boot 项目,其中数据库中包含了一张 userinfo 表,它的组成结构和数

  • Spring中自定义数据类型转换的方法详解

    目录 类型转换服务 实现Converter接口 实现ConverterFactory接口 实现GenericConverter接口 环境:Spring5.3.12.RELEASE. Spring 3引入了一个core.onvert包,提供一个通用类型转换系统.系统定义了一个SPI来实现类型转换逻辑,以及一个API来在运行时执行类型转换.在Spring容器中,可以使用这个系统作为PropertyEditor实现的替代,将外部化的bean属性值字符串转换为所需的属性类型.还可以在应用程序中需要类型转

  • spring中的FactoryBean代码示例

    上篇文章中我们介绍了浅谈Spring的两种配置容器,接下来我们就了解下spring中的FactoryBean的相关内容,具体如下. 从SessionFactory说起: 在使用SSH集成开发的时候,我们有时候会在applicationContext.xml中配置Hibernate的信息,下面是配置SessionFactory的一段示例代码: <bean id="sessionFactory" class="org.springframework.orm.hibernat

  • 关于spring中定时器的使用教程

    前言 在很多实际的web应用中,都有需要定时实现的服务,如每天12点推送个新闻,每隔一个小时提醒用户休息一下眼睛,隔一段时间检测用户是否离线等等. spring框架提供了对定时器的支持,通过配置文件就可以很好的实现定时器,只需要应用启动,就自动启动定时器.下面介绍一下具体做法. 第一种,使用XML配置的方法 前期工作,配置spring的开发环境(这里用到了spring的web应用包,需要导入) 首先创建定时器的任务类,定时器要做什么工作,就在这里写什么方法. package org.time;

随机推荐