[英]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.