This commit is contained in:
@@ -0,0 +1,44 @@
|
|||||||
|
package com.yunhai.userbase.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全局 Jackson 日期格式统一。
|
||||||
|
*
|
||||||
|
* <p>Spring Boot 的 {@code spring.jackson.date-format} 只作用于 {@link java.util.Date},
|
||||||
|
* 对 {@code LocalDateTime}/{@code LocalDate} 无效;且 {@code spring.jackson.local-date-time-format}
|
||||||
|
* 并非 {@code JacksonProperties} 的合法绑定项(会被静默忽略)。本配置把 Nacos 中已配置的
|
||||||
|
* {@code spring.jackson.date-format} 同时应用到 JSR-310 时间类型,做到全局统一。
|
||||||
|
*
|
||||||
|
* <p>仅用 {@code serializerByType}/{@code deserializerByType} 覆盖 JavaTimeModule 默认序列化器,
|
||||||
|
* 不 new 整个 ObjectMapper,因此不会禁用 Spring Boot 的 Jackson 自动配置;
|
||||||
|
* 字段上的 {@code @JsonFormat} 优先级更高,不受影响。
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class JacksonConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(
|
||||||
|
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") String dateFormat) {
|
||||||
|
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat);
|
||||||
|
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
|
return (Jackson2ObjectMapperBuilder builder) -> {
|
||||||
|
builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
|
||||||
|
builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
|
||||||
|
builder.serializerByType(LocalDate.class, new LocalDateSerializer(dateFormatter));
|
||||||
|
builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(dateFormatter));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user