如何在Spring Boot中全局配置`@ DateTimeFormat`模式? [英] How to globally configure `@DateTimeFormat` pattern in Spring Boot?
问题描述
我的Spring Boot应用程序,我有一些控制器接受日期作为查询参数:
Im my Spring Boot application, I have some controllers that accept a date as query parameter:
@RestController
public class MyController {
@GetMapping
public ResponseEntity<?> getDataByDate(
@RequestParam(value = "date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
final LocalDate date) {
return ResponseEntity.ok();
}
}
这很有效,我甚至可以标记参数使用 @RequestParam(value =date,required = false)
作为可选项,然后使用可选< LocalDate>
。 Spring将处理所有这些并在缺少参数时传递一个空的Optional。
This works well, and I can even mark the parameter as optional using @RequestParam(value = "date", required = false)
and then use an Optional<LocalDate>
. Spring will handle all this and pass an empty Optional when the parameter is missing.
由于我有几个控制器使用日期作为查询参数,我想为所有人配置此行为 LocalDate
查询参数。我已经尝试了 spring.mvc.date-pattern
属性,但它似乎只适用于 java.util.Date
。
Since I have several controllers using dates as query parameters, I want to configure this behavior for all LocalDate
query parameters. I have tried the spring.mvc.date-pattern
property, but it only seems to work for java.util.Date
.
所以在搜索网页后,我提出的最好的是 ControllerAdvice
我从这里采用< a href =https://stackoverflow.com/a/43726183/5391954>答案。此解决方案的问题是,无法再处理 Optional< LocalDate>
。感觉这是在Spring Boot中配置行为的错误方法。
So after searching the web, the best I came up with is a ControllerAdvice
I adopted from this answer. The problem with this solution is, that is can not handle Optional<LocalDate>
anymore. It feels like this is the wrong way to configure the behavior in Spring Boot.
所以我的问题是:如何全局配置的模式LocalDate
在Spring Boot中以惯用方式用作查询参数?
So my question is: How do I globally configure the pattern for LocalDate
used as query parameters in an idiomatic way in Spring Boot?
推荐答案
目前这不容易可能(例如,通过设置简单的配置属性),请参阅#5523 。我到目前为止找到的最佳解决方案是注册 Formatter< LocalDate>
。这也适用于建模为可选参数< LocalDate>
的可选参数:
This is currently not easily possible (e.g. by setting a simple configuration property), see #5523. The best solution I found so far is to register a Formatter<LocalDate>
. This will also work with optional parameters modeled as Optional<LocalDate>
:
@Bean
public Formatter<LocalDate> localDateFormatter() {
return new Formatter<LocalDate>() {
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
}
@Override
public String print(LocalDate object, Locale locale) {
return DateTimeFormatter.ISO_DATE.format(object);
}
};
}
当我的提案在<时,可能会使用配置属性设置此项a href =https://github.com/spring-projects/spring-boot/pull/9930\"rel =nofollow noreferrer>#9930 已合并。
这篇关于如何在Spring Boot中全局配置`@ DateTimeFormat`模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!