林我的春节,启动应用程序,我有一些控制器,接受一个日期作为查询参数:如何在Spring Boot中全局配置`@ DateTimeFormat`模式?
@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)
,然后使用Optional<LocalDate>
标记参数为可选。 Spring将处理所有这些,并在参数丢失时传递一个空的可选参数。
由于我有几个控制器使用日期作为查询参数,我想为所有LocalDate
查询参数配置此行为。我试过spring.mvc.date-pattern
属性,但它似乎只适用于java.util.Date
。
于是在网上搜索后,最好的我想出了一个ControllerAdvice
我从这个answer采用。这个解决方案的问题是,这是无法处理Optional<LocalDate>
了。感觉这是在Spring Boot中配置行为的错误方法。
所以我的问题是:我如何全局配置在春季启动的惯用方式使用查询参数LocalDate
模式?
这看起来像它的方式在全球范围使用ControllerAdvice做。另见https://stackoverflow.com/questions/40644368/setting-default-datetimeformat-annotation-in-spring。 – selvinsource
正如我所说,这种解决方案不处理'可选',它不觉得我习惯。应该有一些配置属性来轻松设置它。 –
britter
看起来这是不容易的。见https://github.com/spring-projects/spring-boot/issues/5523 – britter