How to globally configure the `@ DateTimeFormat` template in Spring Download?

Im my Spring Download the application, I have some controllers that accept the date as a request parameter:

@RestController public class MyController { @GetMapping public ResponseEntity<?> getDataByDate( @RequestParam(value = "date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) final LocalDate date) { return ResponseEntity.ok(); } } 

This works well, and I can even mark the parameter as optional using @RequestParam(value = "date", required = false) and then use Optional<LocalDate> . Spring will handle all this and pass an empty parameter. Optional when this parameter is missing.

Since I have several controllers that use dates as query parameters, I want to configure this behavior for all LocalDate query LocalDate . I tried the spring.mvc.date-pattern property, but it only works for java.util.Date .

Thus, after searching the Internet, I got the best result from the ControllerAdvice , which I accepted from this. The problem with this solution is that it can no longer handle Optional<LocalDate> . This seems to be the wrong way to configure behavior in Spring Boot.

So my question is: how to globally configure the template for LocalDate used as query parameters in idiomatic mode in Spring Boot?

+5
source share
1 answer

This is currently not so easy (for example, setting a simple configuration property), see # 5523 . The best solution I've found so far is to register a Formatter<LocalDate> . This will also work with additional 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); } }; } 

Perhaps this can be set using the configuration property when my proposal in # 9930 was merged.

+1
source

Source: https://habr.com/ru/post/1270436/


All Articles