千家信息网

如何使用@DateTimeFormat和@NumberFormat

发表于:2024-09-23 作者:千家信息网编辑
千家信息网最后更新 2024年09月23日,本篇内容介绍了"如何使用@DateTimeFormat和@NumberFormat"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望
千家信息网最后更新 2024年09月23日如何使用@DateTimeFormat和@NumberFormat

本篇内容介绍了"如何使用@DateTimeFormat和@NumberFormat"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

本文提纲


版本约定

  • Spring Framework:5.3.x

  • Spring Boot:2.4.x

正文

据我了解,@DateTimeFormat是开发中出镜率很高的一个注解,其作用见名之意很好理解:对日期时间格式化。但使用起来常常迷糊。比如:使用它还是com.fasterxml.jackson.annotation.JsonFormat注解呢?能否使用在Long类型上?能否使用在JSR 310日期时间类型上?

有这些问号其实蛮正常,但切忌囫囵吞枣,也不建议强记这些问题的答案,而是通过规律在原理层面去理解,不仅能更牢靠而且更轻松,这或许是学习编程最重要的必备技巧之一。

@DateTimeFormat和@NumberFormat

在类型转换/格式化方面注解,Spring提供了两个:

  • @DateTimeFormat:将Field/方法参数格式化为日期/时间类型

  • @NumberFormat:将Field/方法参数格式化为数字类型

值得关注的是:这里所说的日期/时间类型有很多,如最古老的java.util.Date类型、JSR 310的LocalDate类型甚至时间戳Long类型都可称作日期时间类型;同样的,数字类型也是个泛概念,如Number类型、百分数类型、钱币类型也都属此范畴。

  • ❝话外音:这两个注解能够作用的类型很广很广❞分别看看这两个注解定义,不可谓不简单:

  1. @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})

  2. public @interface DateTimeFormat {

  3. String style() default "SS";

  4. ISO iso() default ISO.NONE;

  5. String pattern() default "";

  6. }


@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) public @interface NumberFormat {   Style style() default Style.DEFAULT;  String pattern() default ""; }

哥俩有两个共通的点:

  1. 鸿蒙官方战略合作共建--HarmonyOS技术社区

  2. 都支持标注在方法Method、字段Field、方法参数Parameter上

  3. 均支持灵活性极大的pattern属性,此属性支持Spring占位符书写形式

  4. 对于pattern属性你既可以用字面量写死,也可以用形如${xxx.xxx.pattern}占位符形式这种更富弹性的写法

咱们在使用这两个注解时,最最最常用的是pattern这个属性没有之一,理由是它非常的灵活强大,能满足各式各样格式化需求。从这一点也侧面看出,咱们在日期/时间、数字方面的格式化,并不遵循国际标准(如ISO),而普遍使用的"中国标准"。

由于这两个注解几乎所有同学都在Spring MVC上使用过,那么本文就先原理再示例。在知晓了其背后原理后再去使用,别有一番体会。

AnnotationFormatterFactory

说到格式化注解,就不得不提该工厂类,它是实现原理的核心所在。

字面含义:注解格式化工厂。用大白话解释:该工厂用于为标注在Field字段上的注解创建对应的格式化器进而对值进行格式化处理。从这句话里可提取出几个关键因素:


  1. 鸿蒙官方战略合作共建--HarmonyOS技术社区

  2. 注解

  3. 字段Field

  4. 这里Field并不只表示java.lang.reflect.Field,像方法返回类型、参数类型都属此范畴,下面使用示例会有所体会

  5. 格式化器Formatter

接口定义:

public interface AnnotationFormatterFactory {    Set> getFieldTypes();    Printer getPrinter(A annotation, Class fieldType);  Parser getParser(A annotation, Class fieldType); }

接口共定义了三个方法:

此接口Spring内建有如下实现:


虽然实现有5个之多,但其实只有两类,也就是说面向使用者而言只需做两种区分即可,分别对应上面所讲的两个注解。这里A哥把它绘制成图所示:


红色框框部分(以及其处理的Field类型)是咱们需要关注的重点,其它的留个印象即可。

关于日期时间类型,我在多篇文章里不再推荐使用java.util.Date类型(更不建议使用Long类型喽),而是使用Java 8提供的JSR 310日期时间类型100%代替(包括代替joda-time)。但是呢,在当下阶段java.util.Date类型依旧不可忽略(庞大存量市场,庞大"存量"程序员的存在),因此决定把DateTimeFormatAnnotationFormatterFactory依旧还是抬到桌面上来叙述叙述,但求做得更全面些。

❝关于JDK的日期时间我写了一个非常全的系列,详情点击这里直达:日期时间系列,建议先行了解❞

DateTimeFormatAnnotationFormatterFactory

对应的格式化器API是:org.springframework.format.datetime.DateFormatter。

@since 3.2版本就已存在,专用于对java.util.Date体系 + @DateTimeFormat的支持:创建出相应的Printer/Parser。下面解读其源码:


①:该工厂类专为@DateTimeFormat注解服务②:借助Spring的StringValueResolver对占位符(若存在)做替换


这部分源码告诉我们:@DateTimeFormat注解标注在如图的这些类型上时才有效,才能被该工厂处理从而完成相应创建工作。


核心处理逻辑也比较好理解:不管是Printer还是Parser最终均委托给DateFormatter去完成,而此API在本系列前面文章已做了详细讲解。电梯直达

值得注意的是:DateFormatter 只能 处理Date类型。换句话讲getFormatter()方法的第二个参数fieldType在此方法里并没有被使用,也就是说缺省情况下@DateTimeFormat注解并不能正常处理其标注在Calendar、Long类型的Case。若要得到支持,需自行重写其getPrinter/getParser等方法。

使用示例

由于@DateTimeFormat可以标注在成员属性、方法参数、方法(返回值)上,且当其标注在Date、Calendar、Long等类型上时方可交给本工厂类来处理生成相应的处理类,本文共用三个案例case进行覆盖。

case1:成员属性 + Date类型。输入 + 输出

准备一个标注有@DateTimeFormat注解的Field属性,为Date类型

@Data @AllArgsConstructor class Person {      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")     private Date birthday;      }

书写测试程序:

@Test public void test1() throws Exception {     AnnotationFormatterFactory annotationFormatterFactory = new DateTimeFormatAnnotationFormatterFactory();      // 找到该field     Field field = Person.class.getDeclaredField("birthday");     DateTimeFormat annotation = field.getAnnotation(DateTimeFormat.class);     Class type = field.getType();      // 输出:     System.out.println("输出:Date -> String====================");     Printer printer = annotationFormatterFactory.getPrinter(annotation, type);     Person person = new Person(new Date());     System.out.println(printer.print(person.getBirthday(), Locale.US));      // 输入:     System.out.println("输入:String -> Date====================");     Parser parser = annotationFormatterFactory.getParser(annotation, type);     Object output = parser.parse("2021-02-06 19:00:00", Locale.US);     person = new Person((Date) output);     System.out.println(person); }

运行程序,输出:

输出:Date -> String==================== 2021-02-06 22:21:56 输入:String -> Date==================== Person(birthday=Sat Feb 06 19:00:00 CST 2021)

完美。

case2:方法参数 + Calendar。输入

@Test public void test2() throws NoSuchMethodException, ParseException {     AnnotationFormatterFactory annotationFormatterFactory = new DateTimeFormatAnnotationFormatterFactory();      // 拿到方法入参     Method method = this.getClass().getDeclaredMethod("method", Calendar.class);     Parameter parameter = method.getParameters()[0];     DateTimeFormat annotation = parameter.getAnnotation(DateTimeFormat.class);     Class type = parameter.getType();      // 输入:     System.out.println("输入:String -> Calendar====================");     Parser parser = annotationFormatterFactory.getParser(annotation, type);     Object output = parser.parse("2021-02-06 19:00:00", Locale.US);  // 给该方法传入"转换好的"参数,表示输入     method((Calendar) output); }  public void method(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Calendar calendar) {     System.out.println(calendar);     System.out.println(calendar.getTime()); }

运行程序,报错:

输入:String -> Calendar====================  java.lang.ClassCastException: java.util.Date cannot be cast to java.util.Calendar  ...

通过文上的阐述,这个错误是在意料之中的。下面通过自定义一个增强实现来达到目的:

class MyDateTimeFormatAnnotationFormatterFactory extends DateTimeFormatAnnotationFormatterFactory {      @Override     public Parser getParser(DateTimeFormat annotation, Class fieldType) {         if (fieldType.isAssignableFrom(Calendar.class)) {             return new Parser() {                 @Override                 public Calendar parse(String text, Locale locale) throws ParseException {                     // 先翻译为Date                     Formatter formatter = getFormatter(annotation, fieldType);                     Date date = formatter.parse(text, locale);                      // 再翻译为Calendar                     Calendar calendar = Calendar.getInstance(TimeZone.getDefault());                     calendar.setTime(date);                     return calendar;                 }              };         }         return super.getParser(annotation, fieldType);     } }

将测试程序中的工厂类换为自定义的增强实现:

AnnotationFormatterFactory annotationFormatterFactory = new MyDateTimeFormatAnnotationFormatterFactory();

再次运行程序,输出:

输入:String -> Calendar==================== java.util.GregorianCalendar[time=1612609200000, ... Sat Feb 06 19:00:00 CST 2021

完美。

case3:方法返回值 + Long。输出 建议自行实现,略

❝时间戳被经常用来做时间传递,那么传输中的Long类型如何被自动封装 为Date类型(输入)呢?动动手巩固下吧~❞

Jsr310DateTimeFormatAnnotationFormatterFactory

对应的格式化器API是:Spring的org.springframework.format.datetime.standard.DateTimeFormatterFactory以及JDK的java.time.format.DateTimeFormatter。

@since 4.0。JSR 310时间是伴随着Java 8的出现而出现的,Spring自4.0 开始支持 Java 8,自5.0至少基于 Java 8,因此此类since 4.0就不好奇喽。

从类名能读出它用于处理JSR 310日期时间。下面解读一下它的部分源码,透过现象看其本质:


①:该工厂专为@DateTimeFormat注解服务②:借助Spring的StringValueResolver对占位符(若存在)做替换


@DateTimeFormat注解标注在这些类型上时,就会交给此工厂类来负责其格式化器的创建工作。


①:得到一个JDK的java.time.format.DateTimeFormatter,由它负责将 日期/时间 -> String类型的格式化。由于JSR 310日期/时间的格式化JDK自己实现得已经非常完善,Spring只需要将它整合进来就成。但是呢,DateTimeFormatter它是线程安全的无法同时设置iso、pattern等个性化参数,于是Spring就造了DateTimeFormatterFactory工厂类,用它用来抹平使用上的差异,达到(和java.util.Date)一致的使用体验。当然喽,这个知识点属于上篇文章的内容,欲回顾详情可点击这里电梯直达。

回到本处,getFormatter()方法得到格式化器实例是关键,具体代码如下:


使用Spring的工厂类DateTimeFormatterFactory构建出一个JSR 310的日期时间格式化器DateTimeFormatter来处理。有了上篇文章的铺垫,相信这个逻辑无需再多费一言解释了哈。

②:这一大块是对LocalXXX(含LocalDate/Time)标准格式化器做的特殊处理:将ISO_XXX格式化模版适配为更加适用的ISO_Local_XXX格式化模版,更加精确。③:TemporalAccessorPrinter它就是个Printer,实际的格式化器依旧是DateTimeFormatter,只不过它的作用是兼容到了上下文级别(和当前线程绑定)的格式化器,从而有能力用到上下文级别的格式化参数,具有更好的可定制性,如下图所示(源码来自TemporalAccessorPrinter):


强调:别看这个特性很小,但非常有用,有四两拨千斤的功效。因为它和我们业务系统息息相关,掌握这个点可轻松实现事半功倍的效果,别人加班你加薪。关于此知识点的应用,A哥觉得值得专门写篇文章来描述,敬请期待下文。

接下来再看看getParser()部分的实现:


①:TemporalAccessorParser是个Parser,同样的也是利用了具有Context上下文特性的DateTimeFormatter来完成String -> TemporalAccessor工作的。熟悉这个方向的转换逻辑的同学就知道,因为都是静态方法调用,所以必须用"枚举"的方式一一处理,截图如下(源码来自TemporalAccessorParser):


到此,整个Jsr310DateTimeFormatAnnotationFormatterFactory的源码就分析完了,总结一下:

  1. 鸿蒙官方战略合作共建--HarmonyOS技术社区

  2. 此工厂专为标注在JSR 310日期/时间类型的@DateTimeFormat注解服务

  3. 底层格式化器双向均使用的是和上下文相关的的DateTimeFormatter,具有高度可定制化的特性。此特性虽小却有四两拨千斤的效果,后面会专文给出使用场景

  4. @DateTimeFormat注解的style和pattern属性都是支持占位符形式书写的,更富弹性

使用示例

它不像DateTimeFormatAnnotationFormatterFactory只提供了部分支持,而是提供了全部功能,感受一下。

case1:成员属性 + LocalDate类型。输入 + 输出

@Data @AllArgsConstructor class Father {     @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)     private LocalDate birthday; }

测试代码:

@Test public void test4() throws NoSuchFieldException, ParseException {     AnnotationFormatterFactory annotationFormatterFactory = new Jsr310DateTimeFormatAnnotationFormatterFactory();      // 找到该field     Field field = Father.class.getDeclaredField("birthday");     DateTimeFormat annotation = field.getAnnotation(DateTimeFormat.class);     Class type = field.getType();      // 输出:     System.out.println("输出:LocalDate -> String====================");     Printer printer = annotationFormatterFactory.getPrinter(annotation, type);     Father father = new Father(LocalDate.now());     System.out.println(printer.print(father.getBirthday(), Locale.US));      // 输入:     System.out.println("输入:String -> Date====================");     Parser parser = annotationFormatterFactory.getParser(annotation, type);     Object output = parser.parse("2021-02-07", Locale.US);     father = new Father((LocalDate) output);     System.out.println(father); }

运行程序,输出:

输出:LocalDate -> String==================== 2021-02-07 输入:String -> Date==================== Father(birthday=2021-02-07)

完美。

case2:方法参数 + LocalDate类型。输入

@Test public void test5() throws ParseException, NoSuchMethodException {     AnnotationFormatterFactory annotationFormatterFactory = new Jsr310DateTimeFormatAnnotationFormatterFactory();      // 拿到方法入参     Method method = this.getClass().getDeclaredMethod("methodJSR310", LocalDate.class);     Parameter parameter = method.getParameters()[0];     DateTimeFormat annotation = parameter.getAnnotation(DateTimeFormat.class);     Class type = parameter.getType();       // 输入:     System.out.println("输入:String -> LocalDate====================");     Parser parser = annotationFormatterFactory.getParser(annotation, type);     Object output = parser.parse("2021-02-06", Locale.US);     // 给该方法传入"转换好的"参数,表示输入     methodJSR310((LocalDate) output); }  public void methodJSR310(@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate localDate) {     System.out.println(localDate); }

运行程序,输出:

输入:String -> LocalDate==================== 2021-02-06

case3:方法返回值 + LocalDate类型。输入

@Test public void test6() throws NoSuchMethodException {     AnnotationFormatterFactory annotationFormatterFactory = new Jsr310DateTimeFormatAnnotationFormatterFactory();      // 拿到方法返回值类型     Method method = this.getClass().getDeclaredMethod("method1JSR310");     DateTimeFormat annotation = method.getAnnotation(DateTimeFormat.class);     Class type = method.getReturnType();       // 输出:     System.out.println("输出:LocalDate -> 时间格式的String====================");     Printer printer = annotationFormatterFactory.getPrinter(annotation, type);      LocalDate returnValue = method1JSR310();     System.out.println(printer.print(returnValue, Locale.US)); }  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) public LocalDate method1JSR310() {     return LocalDate.now(); }

完美。

NumberFormatAnnotationFormatterFactory

对应的格式化器API是:org.springframework.format.number.AbstractNumberFormatter的三个子类


@since 3.0。直奔主题,源码喽几眼:


有了上面的"经验",此part不用解释了吧。

①:@NumberFormat可以标注在Number的子类型上,并生成对应的格式化器处理。

底层实现:实际的格式化动作Printer/Parser如下图所示,全权委托给前面已介绍过的格式化器来完成,就不做过多介绍啦。有知识盲区的可乘坐电梯前往本系列前面文章查看~


使用示例

@NumberFormat支持标注在多种类型上,如小数、百分数、钱币等等,由于文上已做好了铺垫,所以这里只给出个简单使用案例即可,举一反三。

@Test public void test2() throws NoSuchMethodException, ParseException {     AnnotationFormatterFactory annotationFormatterFactory = new NumberFormatAnnotationFormatterFactory();      // 获取待处理的目标类型(方法参数、字段属性、方法返回值等等)     Method method1 = this.getClass().getMethod("method2", double.class);     Parameter parameter = method1.getParameters()[0];     NumberFormat annotation = parameter.getAnnotation(NumberFormat.class);     Class fieldType = parameter.getType();      // 1、根据注解和field类型生成一个解析器,完成String -> LocalDateTime     Parser parser = annotationFormatterFactory.getParser(annotation, fieldType);     // 2、模拟转换动作,并输出结果     Object result = parser.parse("11%", Locale.US);     System.out.println(result.getClass());     System.out.println(result);  }  public void method2(@NumberFormat(style = NumberFormat.Style.PERCENT) double d) { }

运行程序,输出:

class java.math.BigDecimal 0.11

完美的将11%这种百分数数字转换为BigDecimal了。至于为何是BigDecimal类型而不是double,那都在PercentStyleFormatter里了。

"如何使用@DateTimeFormat和@NumberFormat"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

类型 格式 注解 方法 输入 时间 输出 日期 处理 参数 工厂 属性 支持 程序 两个 源码 运行 文章 知识 示例 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 湖南郴州软件开发工程师待遇 苏州爱搭网络技术有限公司 网络安全问题的总结 浙江java软件开发自学步骤 审计网络安全意识淡薄 网络数据库之发展前景趋势 局域网服务器软件 合肥旭实互联网科技有限公司 阿里云服务器在哪里开启端口 数据库系统中并发控制的方法 银行数据库安全性措施 护苗 网络安全课三 网络安全法突出的亮点在于 服务器周转车3d图 郴州市软件开发工程师培训中心 山东办公系统软件开发公司 网络安全规范的重要意义 没有电脑如何学会网络技术 数据库基础与应用综合题 如何清除一张表中的数据库 净化网络安全守护精神家园 跨平台软件开发方案 亚细胞定位预测数据库使用 访问远程mysql数据库 三门峡nas存储服务器 网络安全防卫手册pdf 大专软件开发工程师证 软件开发等级 p级 抖音网络安全条例 数据库关系模型中所谓的关系
0