How to use LocalDateTime RequestParam in Spring? I get “Failed to convert String to LocalDateTime”

后端 未结 10 1442
小蘑菇
小蘑菇 2020-11-29 02:35

I use Spring Boot and included jackson-datatype-jsr310 with Maven:


    com.fasterxml.jackson.datatype         


        
10条回答
  •  爱一瞬间的悲伤
    2020-11-29 02:36

    I ran into the same problem and found my solution here (without using Annotations)

    ...you must at least properly register a string to [LocalDateTime] Converter in your context, so that Spring can use it to automatically do this for you every time you give a String as input and expect a [LocalDateTime]. (A big number of converters are already implemented by Spring and contained in the core.convert.support package, but none involves a [LocalDateTime] conversion)

    So in your case you would do this:

    public class StringToLocalDateTimeConverter implements Converter {
        public LocalDateTime convert(String source) {
            DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
            return LocalDateTime.parse(source, formatter);
        }
    }
    

    and then just register your bean:

    
    

    With Annotations

    add it to your ConversionService:

    @Component
    public class SomeAmazingConversionService extends GenericConversionService {
    
        public SomeAmazingConversionService() {
            addConverter(new StringToLocalDateTimeConverter());
        }
    
    }
    

    and finally you would then @Autowire in your ConversionService:

    @Autowired
    private SomeAmazingConversionService someAmazingConversionService;
    

    You can read more about conversions with spring (and formatting) on this site. Be forewarned it has a ton of ads, but I definitely found it to be a useful site and a good intro to the topic.

提交回复
热议问题