全局配置
作用?配置一次,全局起作用。但是只能配置一种,要么是时间(即年月日时分秒),要么是日期(即年月日)。
在哪里配置?xml配置文件。
# 日期格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false
自定义转换类
全局配置只能配置一种,另外一种需要实现自定义类。
具体分两步, 1.自定义类
package com.wz.bpm.common;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String,Date> {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date convert(String s) {
if ("".equals(s) || s == null) {
return null;
}
try {
return simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
2.java配置
package com.wz.bpm.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.wz.bpm.common.DateConverter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter()); //这里配置
}
@Bean
public ExecutorService executorService() {
return Executors.newCachedThreadPool();
}
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("*");
}
}
json格式的数据
背景
上面的解决方法,对json格式的数据,不能生效。即json格式的日期数据,不走自定义转换类,而表单的日期数据会自动走自定义转换类。
解决方法-非全局
每个字段,都添加注解。
@JsonFormat(pattern="yyyy-MM-dd")
private Date salaryDate;
解决方法2-全局处理
待解决。
参考
www.baeldung.com/spring-boot… juejin.cn/post/684490… segmentfault.com/a/119000001…