自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

3種 Springboot 全局時(shí)間格式化方式,別再寫重復(fù)代碼了

開發(fā) 前端
時(shí)間格式化在項(xiàng)目中使用頻率是非常高的,當(dāng)我們的 API 接口返回結(jié)果,需要對(duì)其中某一個(gè) date 字段屬性進(jìn)行特殊的格式化處理,通常會(huì)用到 SimpleDateFormat 工具處理。

 [[340290]]

本文轉(zhuǎn)載自微信公眾號(hào)「程序員內(nèi)點(diǎn)事」,作者程序員內(nèi)點(diǎn)事 。轉(zhuǎn)載本文請(qǐng)聯(lián)系程序員內(nèi)點(diǎn)事公眾號(hào)。

時(shí)間格式化在項(xiàng)目中使用頻率是非常高的,當(dāng)我們的 API 接口返回結(jié)果,需要對(duì)其中某一個(gè) date 字段屬性進(jìn)行特殊的格式化處理,通常會(huì)用到 SimpleDateFormat 工具處理。

  1. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
  2. Date stationTime = dateFormat.parse(dateFormat.format(PayEndTime())); 

可一旦處理的地方較多,不僅 CV 操作頻繁,還產(chǎn)生很多重復(fù)臃腫的代碼,而此時(shí)如果能將時(shí)間格式統(tǒng)一配置,就可以省下更多時(shí)間專注于業(yè)務(wù)開發(fā)了。

可能很多人覺得統(tǒng)一格式化時(shí)間很簡(jiǎn)單啊,像下邊這樣配置一下就行了,但事實(shí)上這種方式只對(duì) date 類型生效。

  1. spring.jackson.date-format=yyyy-MM-dd HH:mm:ss 
  2. spring.jackson.time-zone=GMT+8 

而很多項(xiàng)目中用到的時(shí)間和日期API 比較混亂, java.util.Date 、 java.util.Calendar 和 java.time LocalDateTime 都存在,所以全局時(shí)間格式化必須要同時(shí)兼容性新舊 API。

看看配置全局時(shí)間格式化前,接口返回時(shí)間字段的格式。

  1. @Data 
  2. public class OrderDTO { 
  3.  
  4.     private LocalDateTime createTime; 
  5.  
  6.     private Date updateTime; 

很明顯不符合頁(yè)面上的顯示要求(有人抬杠為啥不讓前端解析時(shí)間,我只能說睡服代碼比說服人容易得多~)

 

 


未做任何配置的結(jié)果

 

 

一、@JsonFormat 注解

@JsonFormat 注解方式嚴(yán)格意義上不能叫全局時(shí)間格式化,應(yīng)該叫部分格式化,因?yàn)锧JsonFormat 注解需要用在實(shí)體類的時(shí)間字段上,而只有使用相應(yīng)的實(shí)體類,對(duì)應(yīng)的字段才能進(jìn)行格式化。

  1. @Data 
  2. public class OrderDTO { 
  3.  
  4.     @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd"
  5.     private LocalDateTime createTime; 
  6.  
  7.     @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss"
  8.     private Date updateTime; 

字段加上 @JsonFormat 注解后,LocalDateTime 和 Date 時(shí)間格式化成功。

@JsonFormat 注解格式化

 

二、@JsonComponent 注解(推薦)

這是我個(gè)人比較推薦的一種方式,前邊看到使用 @JsonFormat 注解并不能完全做到全局時(shí)間格式化,所以接下來(lái)我們使用 @JsonComponent 注解自定義一個(gè)全局格式化類,分別對(duì) Date 和 LocalDate 類型做格式化處理。

  1. @JsonComponent 
  2. public class DateFormatConfig { 
  3.  
  4.     @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}"
  5.     private String pattern; 
  6.  
  7.     /** 
  8.      * @author xiaofu 
  9.      * @description date 類型全局時(shí)間格式化 
  10.      * @date 2020/8/31 18:22 
  11.      */ 
  12.     @Bean 
  13.     public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() { 
  14.  
  15.         return builder -> { 
  16.             TimeZone tz = TimeZone.getTimeZone("UTC"); 
  17.             DateFormat df = new SimpleDateFormat(pattern); 
  18.             df.setTimeZone(tz); 
  19.             builder.failOnEmptyBeans(false
  20.                     .failOnUnknownProperties(false
  21.                     .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) 
  22.                     .dateFormat(df); 
  23.         }; 
  24.     } 
  25.  
  26.     /** 
  27.      * @author xiaofu 
  28.      * @description LocalDate 類型全局時(shí)間格式化 
  29.      * @date 2020/8/31 18:22 
  30.      */ 
  31.     @Bean 
  32.     public LocalDateTimeSerializer localDateTimeDeserializer() { 
  33.         return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); 
  34.     } 
  35.  
  36.     @Bean 
  37.     public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { 
  38.         return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer()); 
  39.     } 

看到 Date 和 LocalDate 兩種時(shí)間類型格式化成功,此種方式有效。

@JsonComponent 注解處理格式化

 

但還有個(gè)問題,實(shí)際開發(fā)中如果我有個(gè)字段不想用全局格式化設(shè)置的時(shí)間樣式,想自定義格式怎么辦?

那就需要和 @JsonFormat 注解配合使用了。

  1. @Data 
  2. public class OrderDTO { 
  3.  
  4.     @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd"
  5.     private LocalDateTime createTime; 
  6.  
  7.     @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd"
  8.     private Date updateTime; 

從結(jié)果上我們看到 @JsonFormat 注解的優(yōu)先級(jí)比較高,會(huì)以 @JsonFormat 注解的時(shí)間格式為主。

 

三、@Configuration 注解

這種全局配置的實(shí)現(xiàn)方式與上邊的效果是一樣的。

“注意:在使用此種配置后,字段手動(dòng)配置@JsonFormat 注解將不再生效。”

  1. @Configuration 
  2. public class DateFormatConfig2 { 
  3.  
  4.     @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}"
  5.     private String pattern; 
  6.  
  7.     public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
  8.  
  9.     @Bean 
  10.     @Primary 
  11.     public ObjectMapper serializingObjectMapper() { 
  12.         ObjectMapper objectMapper = new ObjectMapper(); 
  13.         JavaTimeModule javaTimeModule = new JavaTimeModule(); 
  14.         javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer()); 
  15.         javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer()); 
  16.         objectMapper.registerModule(javaTimeModule); 
  17.         return objectMapper; 
  18.     } 
  19.  
  20.     /** 
  21.      * @author xiaofu 
  22.      * @description Date 時(shí)間類型裝換 
  23.      * @date 2020/9/1 17:25 
  24.      */ 
  25.     @Component 
  26.     public class DateSerializer extends JsonSerializer<Date> { 
  27.         @Override 
  28.         public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException { 
  29.             String formattedDate = dateFormat.format(date); 
  30.             gen.writeString(formattedDate); 
  31.         } 
  32.     } 
  33.  
  34.     /** 
  35.      * @author xiaofu 
  36.      * @description Date 時(shí)間類型裝換 
  37.      * @date 2020/9/1 17:25 
  38.      */ 
  39.     @Component 
  40.     public class DateDeserializer extends JsonDeserializer<Date> { 
  41.  
  42.         @Override 
  43.         public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { 
  44.             try { 
  45.                 return dateFormat.parse(jsonParser.getValueAsString()); 
  46.             } catch (ParseException e) { 
  47.                 throw new RuntimeException("Could not parse date", e); 
  48.             } 
  49.         } 
  50.     } 
  51.  
  52.     /** 
  53.      * @author xiaofu 
  54.      * @description LocalDate 時(shí)間類型裝換 
  55.      * @date 2020/9/1 17:25 
  56.      */ 
  57.     public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { 
  58.         @Override 
  59.         public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { 
  60.             gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern))); 
  61.         } 
  62.     } 
  63.  
  64.     /** 
  65.      * @author xiaofu 
  66.      * @description LocalDate 時(shí)間類型裝換 
  67.      * @date 2020/9/1 17:25 
  68.      */ 
  69.     public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { 
  70.         @Override 
  71.         public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException { 
  72.             return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern)); 
  73.         } 
  74.     } 

 

總結(jié)

分享了一個(gè)簡(jiǎn)單卻又很實(shí)用的 Springboot 開發(fā)技巧,其實(shí)所謂的開發(fā)效率,不過是一個(gè)又一個(gè)開發(fā)技巧堆砌而來(lái),聰明的程序員總是能用最少的代碼完成任務(wù)。

責(zé)任編輯:武曉燕 來(lái)源: 程序員內(nèi)點(diǎn)事
相關(guān)推薦

2022-09-05 08:06:36

SpringBoot時(shí)間格式化

2021-07-26 14:34:02

springboot 時(shí)間格式化項(xiàng)目

2020-06-04 09:18:52

CTOif-else代碼

2020-11-03 10:21:33

MySQL

2022-04-13 10:38:04

Springboot日期時(shí)間格式化

2020-06-15 08:12:51

try catch代碼處理器

2020-06-28 08:26:41

Python開發(fā)工具

2025-01-15 12:31:46

2010-07-29 11:03:53

Flex代碼格式化

2015-01-07 15:21:30

Android Stu代碼格式化

2022-05-13 09:16:49

Python代碼

2010-08-03 10:46:41

Flex代碼格式化

2020-12-04 10:05:00

Pythonprint代碼

2009-09-04 13:19:59

C#代碼格式化

2022-03-10 10:24:45

Vim代碼Linux

2020-12-02 11:18:50

print調(diào)試代碼Python

2022-03-11 12:31:04

Vue3組件前端

2022-01-07 13:34:25

Java時(shí)間格式化

2023-11-01 13:37:38

Golang代碼

2010-08-02 16:25:03

ibmdwJDT
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)