spring mvc 时间格式序列化,反序列化配置
在spring mvc 项目中使用 LocalDateTime、LocalDate、LocalTime等时间类型时,为了统一般会使用 @JsonFormat、 @DateTimeFormat 注解进行格式化。但是项目当前一般使用的地方都比较多,每一个地方都加上注解,太麻烦了。所以为了简便,特意总结了下面一套配置时间格式化的配置。方便以后使用
/**
* 时间格式序列化,反序列化,格式处理
*/
@Configuration
public class DateformatConfig {
/**
* Date格式化字符串
*/
private static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* DateTime格式化字符串
*/
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* Time格式化字符串
*/
private static final String TIME_FORMAT = "HH:mm:ss";
/**
* 自定义Bean
*
* @return
*/
@Bean
@Primary
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
// serializerByType 序列化字符串 --》 @JsonFormat
return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)))
.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT)))
// 反序列化为具体对象类型(url 传参不支持) --> @DateTimeFormat
.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)))
.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
}
/**
* 时间LocalDateTime转换
* 通过url 传参的时候使用
* @DateTimeFormat
*/
@Component
public static class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DATETIME_FORMAT));
}
throw new IllegalArgumentException("Invalid value '" + source + "'");
}
}
/**
* 时间LocalDate转换
*/
@Component
public static class LocalDateConverter implements Converter<String, LocalDate> {
@Override
public LocalDate convert(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
return LocalDate.parse(source, DateTimeFormatter.ofPattern(DATE_FORMAT));
}
throw new IllegalArgumentException("Invalid value '" + source + "'");
}
}
}