Spring deserializes a LocalDate in a @RequestBody differently from one in a @RequestParam - why, and can they be the same?

前端 未结 2 1098
遥遥无期
遥遥无期 2021-02-15 17:27

QUESTION: Spring appears to use different deserialization methods for LocalDate depending on whether it appears in a @RequestBody or a request @R

2条回答
  •  旧时难觅i
    2021-02-15 17:53

    Create a Formatter for LocalDate:

    public class LocalDateFormatter implements Formatter {
    
        @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);
        }
    }
    

    Spring 5+: Register the formatter: Implement WebMvcConfigurer in your @Configuration and override addFormatters:

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new LocalDateFormatter());
    }
    

    Spring Boot: Define a @Primary @Bean to override the default formatter:

    @Bean
    @Primary
    public Formatter localDateFormatter() {
        return new LocalDateFormatter();
    }
    

提交回复
热议问题