最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot全局日期格式配置的方法總結(jié)

 更新時(shí)間:2026年01月15日 09:06:03   作者:BillKu  
本文介紹了在SpringBoot中避免在每個(gè)實(shí)體類中重復(fù)設(shè)置@JsonFormat注解的幾種方法,包括全局配置、自定義Jackson配置類、使用Mixin、自定義注解等,推薦使用全局配置,可以簡(jiǎn)化代碼并滿足大部分場(chǎng)景,需要的朋友可以參考下
spring boot中,不想每個(gè)實(shí)體類中都這樣設(shè)置,有什么方法:
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

在Spring Boot中有幾種方法可以避免在每個(gè)實(shí)體類中重復(fù)設(shè)置@JsonFormat注解:

方法一:全局配置(推薦)

application.ymlapplication.properties中配置全局的日期格式:

YAML配置:

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    serialization:
      write-dates-as-timestamps: false

Properties配置:

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false

方法二:自定義Jackson配置類

@Configuration
public class JacksonConfig {
    
    @Bean
    @Primary
    public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
        return builder -> {
            // 設(shè)置全局日期格式
            builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
            builder.timeZone(TimeZone.getTimeZone("GMT+8"));
            
            // 針對(duì)Java 8時(shí)間API的配置
            builder.serializers(new LocalDateTimeSerializer(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            builder.deserializers(new LocalDateTimeDeserializer(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            // 如果需要,也可以配置LocalDate等其他類型
            builder.serializers(new LocalDateSerializer(
                DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            builder.deserializers(new LocalDateDeserializer(
                DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        };
    }
}

方法三:更詳細(xì)的配置類

@Configuration
public class JacksonConfig {
    
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        
        // 設(shè)置Java 8時(shí)間模塊
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        
        // LocalDateTime序列化和反序列化
        javaTimeModule.addSerializer(LocalDateTime.class, 
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class,
            new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        // LocalDate序列化和反序列化
        javaTimeModule.addSerializer(LocalDate.class,
            new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalDate.class,
            new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        
        objectMapper.registerModule(javaTimeModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        
        return objectMapper;
    }
}

方法四:使用Mixin(為特定類型統(tǒng)一配置)

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
abstract class LocalDateTimeMixin {
}

@Configuration
public class JacksonConfig {
    
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer addCustomSerialization() {
        return builder -> {
            builder.mixIn(LocalDateTime.class, LocalDateTimeMixin.class);
        };
    }
}

方法五:自定義注解(如果需要不同格式)

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public @interface DefaultDateTimeFormat {
}

// 使用方式
@DefaultDateTimeFormat
private LocalDateTime createTime;

推薦方案

建議使用方法一(全局配置),最簡(jiǎn)單直接,能滿足大部分場(chǎng)景。

如果項(xiàng)目中有多種不同的日期格式需求,可以:

  1. 使用方法一設(shè)置默認(rèn)格式
  2. 對(duì)于特殊格式的字段,使用@JsonFormat覆蓋全局配置
// 全局使用 yyyy-MM-dd HH:mm:ss
// 特殊字段使用其他格式
@JsonFormat(pattern = "yyyy/MM/dd")
private LocalDate specialDate;

這樣既能減少重復(fù)代碼,又能保持靈活性。

已經(jīng)設(shè)置日期格式:
  jackson:
    # 全局配置日期格式,這樣就不用每個(gè)實(shí)體類的日期屬性使用 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    serialization:
      write-dates-as-timestamps: false
    deserialization:
      adjust-dates-to-context-time-zone: false
 
package com.weiyu.model;
 
import lombok.Data;
 
import java.time.LocalDateTime;
 
/**
 * 打印模板列表 VO
 */
@Data
public class PrintTemplateListVO {
    private Integer id;
    private String templateType;
    private String templateName;
    private String templateCode;
    private String printDirection;
    private Boolean enabled;
    private String createBy;
    private LocalDateTime createTime;
    private String updateBy;
    private LocalDateTime updateTime;
}
 
但是為什么前端顯示的日期內(nèi)容是:2025-12-19T16:17:32.717

這是因?yàn)槿峙渲玫?nbsp;date-format 只對(duì) java.util.Date 類型有效,對(duì)于 Java 8 的 LocalDateTime 類型不生效。需要單獨(dú)配置 Java 8 時(shí)間模塊。

解決方案:

方案一:創(chuàng)建 Jackson 配置類(推薦)

import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class JacksonConfig {

    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder()
            .modulesToInstall(new JavaTimeModule())
            .serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
            .deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
            .simpleDateFormat(DATE_TIME_FORMAT)
            .timeZone(java.util.TimeZone.getTimeZone("GMT+8"));
    }
}

方案二:更完整的配置類

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

@Configuration
public class JacksonConfig {

    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    @Bean
    @Primary
    public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
        return builder -> {
            // 配置 Java 8 時(shí)間模塊
            builder.modulesToInstall(new JavaTimeModule());
            
            // 配置 LocalDateTime 的序列化和反序列化
            builder.serializers(new LocalDateTimeSerializer(
                DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
            builder.deserializers(new LocalDateTimeDeserializer(
                DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
            
            // 其他配置
            builder.simpleDateFormat(DATE_TIME_FORMAT);
            builder.timeZone(TimeZone.getTimeZone("GMT+8"));
            builder.featuresToDisable(
                com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
            );
        };
    }
}

方案三:完整的 ObjectMapper Bean

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        
        // 配置 LocalDateTime
        javaTimeModule.addSerializer(LocalDateTime.class, 
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class,
            new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        mapper.registerModule(javaTimeModule);
        mapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.setTimeZone(java.util.TimeZone.getTimeZone("GMT+8"));
        
        return mapper;
    }
}

方案四:添加依賴(如果未添加)

確保你的 pom.xml 中包含 Jackson Java 8 時(shí)間模塊的依賴:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

驗(yàn)證配置

添加配置后,LocalDateTime 字段應(yīng)該會(huì)正確格式化為 "2025-12-19 16:17:32",而不是 "2025-12-19T16:17:32.717"。

為什么需要單獨(dú)配置?

  • date-format: yyyy-MM-dd HH:mm:ss 只適用于傳統(tǒng)的 java.util.Date
  • LocalDateTime 是 Java 8 引入的新 API,需要額外的 Jackson 模塊支持
  • Spring Boot 默認(rèn)會(huì)注冊(cè) JavaTimeModule,但沒有應(yīng)用自定義格式

建議使用方案一,它比較簡(jiǎn)潔且能解決問題。配置后不需要在每個(gè)實(shí)體類中添加 @JsonFormat 注解。

代碼實(shí)例:

package com.weiyu.config;

import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.format.DateTimeFormatter;

/**
 * Jackson JSON 序列化/反序列化全局配置類
 * <p>
 * 作用:統(tǒng)一配置項(xiàng)目中日期時(shí)間類型的 JSON 格式化方式
 * 解決:LocalDateTime 等 Java 8 時(shí)間類型在前端顯示為 ISO 格式(如:2025-12-19T16:17:32.717)的問題
 * 效果:所有 LocalDateTime 字段將統(tǒng)一格式化為 "yyyy-MM-dd HH:mm:ss"
 * <p>
 * 配置效果總結(jié):
 * 1. 序列化(對(duì)象 → JSON):
 * - LocalDateTime: 格式化為 "yyyy-MM-dd HH:mm:ss"
 * - java.util.Date: 格式化為 "yyyy-MM-dd HH:mm:ss"
 * - 其他 Java 8 時(shí)間類型(LocalDate、LocalTime):使用默認(rèn)格式
 * <p>
 * 2. 反序列化(JSON → 對(duì)象):
 * - 能正確解析 "yyyy-MM-dd HH:mm:ss" 格式的字符串為 LocalDateTime
 * - 也支持其他常見日期格式
 * <p>
 * 3. 優(yōu)勢(shì):
 * - 無需在每個(gè)實(shí)體類的字段上添加 @JsonFormat 注解
 * - 統(tǒng)一整個(gè)項(xiàng)目的日期時(shí)間格式
 * - 同時(shí)支持新舊日期 API(java.util.Date 和 java.time)
 * <p>
 * 4. 注意事項(xiàng):
 * - 如果某個(gè)字段需要特殊格式,仍可使用 @JsonFormat 覆蓋此全局配置
 * - 此配置不會(huì)影響數(shù)據(jù)庫存儲(chǔ),僅影響 JSON 序列化/反序列化
 */
@Configuration  // 聲明這是一個(gè) Spring 配置類,Spring 啟動(dòng)時(shí)會(huì)自動(dòng)掃描并加載
public class JacksonConfig {

    /**
     * 從 application.yml 中讀取日期格式配置
     * 使用默認(rèn)值:如果配置文件中沒有 spring.jackson.date-format,則使用 "yyyy-MM-dd HH:mm:ss"
     */
    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String dateFormat;

    /**
     * 從 application.yml 中讀取時(shí)區(qū)配置
     * 使用默認(rèn)值:如果配置文件中沒有 spring.jackson.time-zone,則使用 "Asia/Shanghai"
     */
    @Value("${spring.jackson.time-zone:Asia/Shanghai}")
    private String timeZone;

    /**
     * 創(chuàng)建并配置 Jackson2ObjectMapperBuilder Bean
     * <p>
     * 這個(gè)方法返回的 Jackson2ObjectMapperBuilder 會(huì)被 Spring 用于創(chuàng)建所有 ObjectMapper 實(shí)例
     * 包括 REST Controller 返回 JSON 時(shí)使用的 ObjectMapper
     *
     * @return 配置好的 Jackson2ObjectMapperBuilder 實(shí)例
     */
    @Bean  // 聲明這是一個(gè) Spring Bean,Spring 容器會(huì)管理它的生命周期
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        // 使用 Builder 模式鏈?zhǔn)脚渲?Jackson
        return new Jackson2ObjectMapperBuilder()
                // 1. 安裝 JavaTimeModule 模塊
                //    作用:讓 Jackson 支持 Java 8 的時(shí)間類型(LocalDateTime、LocalDate、LocalTime等)
                //    如果沒有這個(gè)模塊,Jackson 無法正確處理 Java 8 時(shí)間類型
                .modulesToInstall(new JavaTimeModule())

                // 2. 配置序列化器
                //    作用:將 LocalDateTime、LocalDate、LocalTime 對(duì)象轉(zhuǎn)換為 JSON 字符串時(shí)使用的格式化規(guī)則
                //    示例:LocalDateTime.now() → "2025-12-19 16:17:32"
                .serializers(
                        new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateFormat)),
                        new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                        new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss"))
                )

                // 3. 配置反序列化器
                //    作用:將 JSON 字符串轉(zhuǎn)換為 LocalDateTime 對(duì)象時(shí)使用的解析規(guī)則
                //    示例:"2025-12-19 16:17:32" → LocalDateTime、LocalDate、LocalTime 對(duì)象
                .deserializers(
                        new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateFormat)),
                        new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                        new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss"))
                )

                // 4. 配置傳統(tǒng) java.util.Date 類型的日期格式
                //    作用:傳統(tǒng) Date 類型也使用相同的日期格式
                //    兼容性:確保項(xiàng)目中既有 java.util.Date 也有 java.time 類型時(shí),格式保持一致
                .simpleDateFormat(dateFormat)

                // 5. 配置時(shí)區(qū)
                //    作用:設(shè)置序列化和反序列化時(shí)的默認(rèn)時(shí)區(qū)
                //    重要:時(shí)區(qū)設(shè)置會(huì)影響日期時(shí)間的顯示和解析
                //    "Asia/Shanghai" - 中國標(biāo)準(zhǔn)時(shí)間(UTC+8)
                //    注意:LocalDateTime 不包含時(shí)區(qū)信息,此設(shè)置主要影響 Date 和 Instant 類型
                .timeZone(java.util.TimeZone.getTimeZone(timeZone));
    }
}

以上就是SpringBoot全局日期格式配置的方法總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot全局日期格式配置的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • JAVA項(xiàng)目常用異常處理匯總

    JAVA項(xiàng)目常用異常處理匯總

    這篇文章主要介紹了JAVA項(xiàng)目常用異常處理匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • maven多模塊項(xiàng)目單獨(dú)打包指定模塊jar包方式

    maven多模塊項(xiàng)目單獨(dú)打包指定模塊jar包方式

    這篇文章主要介紹了maven多模塊項(xiàng)目單獨(dú)打包指定模塊jar包方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-09-09
  • Flink實(shí)戰(zhàn)之實(shí)現(xiàn)流式數(shù)據(jù)去重

    Flink實(shí)戰(zhàn)之實(shí)現(xiàn)流式數(shù)據(jù)去重

    流式數(shù)據(jù)是一種源源不斷產(chǎn)生的數(shù)據(jù),本文探索了一種流式大數(shù)據(jù)的實(shí)時(shí)去重方法,不一定適用于所有場(chǎng)景,不過或許可以給面對(duì)相似問題的你一點(diǎn)點(diǎn)啟發(fā),
    2025-03-03
  • Java實(shí)現(xiàn)基于NIO的多線程Web服務(wù)器實(shí)例

    Java實(shí)現(xiàn)基于NIO的多線程Web服務(wù)器實(shí)例

    在本篇文章里小編給大家整理的是關(guān)于Java實(shí)現(xiàn)基于NIO的多線程Web服務(wù)器實(shí)例內(nèi)容,需要的朋友們可以學(xué)習(xí)下。
    2020-03-03
  • Java中的反射機(jī)制詳解

    Java中的反射機(jī)制詳解

    這篇文章主要介紹了Java中的反射機(jī)制詳解的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • Java實(shí)現(xiàn)簡(jiǎn)易界面通訊錄

    Java實(shí)現(xiàn)簡(jiǎn)易界面通訊錄

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)易界面通訊錄,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • 詳解Java中的不可變對(duì)象

    詳解Java中的不可變對(duì)象

    這篇文章主要介紹了Java中的不可變對(duì)象的相關(guān)知識(shí),文中代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以參考下
    2020-06-06
  • Spring Security 前后端分離場(chǎng)景下的會(huì)話并發(fā)管理

    Spring Security 前后端分離場(chǎng)景下的會(huì)話并發(fā)管理

    本文介紹了在前后端分離架構(gòu)下實(shí)現(xiàn)Spring Security會(huì)話并發(fā)管理的問題,傳統(tǒng)Web開發(fā)中只需簡(jiǎn)單配置sessionManagement()即可實(shí)現(xiàn)會(huì)話數(shù)限制,但在前后端分離場(chǎng)景下,由于采用自定義認(rèn)證過濾器替代了默認(rèn)的UsernamePasswordAuthenticationFilter,感興趣的可以了解一下
    2025-08-08
  • idea項(xiàng)目debug模式無法啟動(dòng)的解決

    idea項(xiàng)目debug模式無法啟動(dòng)的解決

    這篇文章主要介紹了idea項(xiàng)目debug模式無法啟動(dòng)的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Spring-AOP 靜態(tài)普通方法名匹配切面操作

    Spring-AOP 靜態(tài)普通方法名匹配切面操作

    這篇文章主要介紹了Spring-AOP 靜態(tài)普通方法名匹配切面操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07

最新評(píng)論

田东县| 临夏市| 驻马店市| 天镇县| 浦北县| 永州市| 崇阳县| 万载县| 美姑县| 容城县| 岐山县| 株洲市| 新民市| 湖口县| 中宁县| 商河县| 花莲市| 四川省| 南江县| 洛隆县| 洞头县| 九龙县| 白银市| 嵊州市| 万山特区| 伊春市| 扎鲁特旗| 宜州市| 新余市| 台州市| 灵丘县| 石河子市| 江西省| 波密县| 定襄县| 青冈县| 绥宁县| 汪清县| 莱西市| 体育| 扬中市|