[英]Spring Boot unable to set global date format for REST API input
我正在尝试为日期时间设置全局格式,这样我就不必注释每个方法或 DTO 字段。
我尝试全局配置它,它的唯一影响是对API 响应,它以特定模式格式化日期。
但它不接受它作为输入格式。
@Configuration
public class DateFormatConfig {
public DateFormatConfig() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
};
}
}
异常消息
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date';
nested exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam
java.util.Date] for value '2022-01-03 19:32:22'; nested exception is java.lang.IllegalArgumentException
....
Caused by: java.lang.IllegalArgumentException: null
at java.base/java.util.Date.parse(Date.java:616) ~[na:na]
at java.base/java.util.Date.<init>(Date.java:274) ~[na:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[na:na]
一个 REST controller 方法,其中调用落地如下
public Response update(@PathVariable("id")
Long id,
@RequestParam(value = "someTime", required = false)
Date someTime)
我对上述配置的期望是,它应该适用于 API 的输入和 output
如果我使用@DateTimeFormat
注释,一切正常,这意味着我必须对每个字段进行此类更改
@RequestParam(value = "someTime", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date someTime
您可以尝试使用以下代码吗。它应该可以工作。
@PostConstruct
public void init() {
// Setting Spring Boot SetTimeZone
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
你应该使用
@Bean
public Converter<String, Date> stringDateConverter() {
return new Converter<String, Date>() {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public Date convert(@NonNull String source) {
return Date.from(formatter.parse(source, LocalDateTime::from).toInstant(ZoneOffset.UTC));
}
};
}
AbstractNamedValueMethodArgumentResolver#resolveArgument
使用WebDataBinder
, WebDataBinder
使用在WebMvcAutoConfiguration.EnableWebMvcConfiguration#mvcConversionService
中注册的ConversionService
,这个转换器会在org.springframework.boot.convert.ApplicationConversionService#addBeans
中注册
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.