SpringBoot配置LocalDateTime的Serializer和Deserializer

spring.jackson.date-format配置项对于Java8新增的时间日期API是无效的,所以要在项目中使用LocalDateTime,就需要自己去配置Serializer和Deserializer。

application.properties配置

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

通过@Value读取配置值

@Configuration
public class DateTimeFormatterConfig {
    @Value("${spring.jackson.date-format}")
    private String pattern;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }
}
共 0 条评论