针对场景
优化SpringBoot项目中实体类的日期属性使用相同的格式化注解的问题。
- 避免注解的重复性编写
- @JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
解决方案
添加配置类:
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
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.ser.LocalTimeSerializer;
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 java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class DateSerializerAndDeserializerConfig {
@Value("${custom.jackson.format.local-date-time:yyyy-MM-dd HH:mm:ss}")
private String localDateTimePattern;
@Value("${custom.jackson.format.local-date:yyyy-MM-dd}")
private String localDatePattern;
@Value("${custom.jackson.format.local-time:HH:mm:ss}")
private String localTimePattern;
@Value("${custom.jackson.format.date:yyyy-MM-dd HH:mm:ss}")
private String datePattern;
@Bean
public LocalDateTimeSerializer localDateTimeSerializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(localDateTimePattern));
}
@Bean
public LocalDateTimeDeserializer localDateTimeDeserializer() {
return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(localDateTimePattern));
}
@Bean
public LocalDateSerializer localDateSerializer() {
return new LocalDateSerializer(DateTimeFormatter.ofPattern(localDatePattern));
}
@Bean
public LocalDateDeserializer localDateDeserializer() {
return new LocalDateDeserializer(DateTimeFormatter.ofPattern(localDatePattern));
}
@Bean
public LocalTimeSerializer localTimeSerializer() {
return new LocalTimeSerializer(DateTimeFormatter.ofPattern(localTimePattern));
}
@Bean
public LocalTimeDeserializer localTimeDeserializer() {
return new LocalTimeDeserializer(DateTimeFormatter.ofPattern(localTimePattern));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer localDateTimeMapperBuilder() {
return builder -> builder
.serializerByType(LocalDateTime.class, localDateTimeSerializer())
.deserializerByType(LocalDateTime.class, localDateTimeDeserializer())
.serializerByType(LocalDate.class, localDateSerializer())
.deserializerByType(LocalDate.class, localDateDeserializer())
.serializerByType(LocalTime.class, localTimeSerializer())
.deserializerByType(LocalTime.class, localTimeDeserializer())
.simpleDateFormat(datePattern);
}
}
- 如果某些实体类中需要特殊的格式,可以使用@JsonFormat注解来进行设置。
|