springboot3.0已经出来几个月了,最低支持jdk17,做个项目练下手
发现LocalDateTime序列化后返回的是一个数组。
就想着配置一个全局的序列化的配置,默认时间和日期的格式
springboot 版本 3.0.3
package com.sunxh.bms.auth.client.web;
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 com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* spring mvc配置类
* sunxh 2023/2/26
*/
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Resource
private MyWebInterceptor myWebInterceptor;
@Resource
private LoggerInterceptor loggerInterceptor;
/**
* 资源跨域设置
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.maxAge(3600);
}
/**
* 请求拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
loggerInterceptor.addInterceptor(registry);
myWebInterceptor.addInterceptor(registry);
}
/**
* 定义全局默认时间序列化
*/
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String DATE_FORMAT = "yyyy-MM-dd";
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.simpleDateFormat(DATE_TIME_FORMAT)
.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
.deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.modulesToInstall(new ParameterNamesModule());
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
}