Java configuration global time format

Java configuration global time format
plan :

  ① Add configuration items to the configuration file:

spring:
    # jackson时间格式化
    jackson:
        time-zone: GMT+8
        date-format: yyyy-MM-dd HH:mm:ss

  ② Add configuration class:

/**
 * @author LXH-404
 * @Classname LocalDateTimeSerializerConfig
 * @Description 全局时间格式序列化配置类 (LocalDateTime类型)
 */
@Configuration
public class LocalDateTimeSerializerConfig {
    
    

    /**
     * 时间格式
     */
    @Value("${spring.jackson.date-format}") 
    private String pattern;

    /**
     * 序列化构造器
     * @return
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
    
    
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 为给定类型配置自定义序列化器。
     * @return
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    
    
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }

}

For special needs, other time formats can be annotated on the attribute:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

Guess you like

Origin blog.csdn.net/AKALXH/article/details/116239179