title: 如何让接口支持时间格式化字符串自动转 LocalDateTime
id: 20240810203052
aliases:
date: 2024-08-10 20:30:52
tags:
- spring
- ConversionService
需求:支持时间格式化字符串自动转 LocalDateTime
GET http://localhost:8080/doc20240810/test?time=2024-08-10 16:53:03
@RestController
@RequestMapping("doc20240810")
@RequiredArgsConstructor
@Slf4j
public class DemoController {
@GetMapping("test")
public String test(@RequestParam LocalDateTime time) {
return MessageFormat.format("成功获取到time={0}", time);
}
}
如何让Spring 支持对于以上场景的支持?
1、实现 org.springframework.core.convert.converter.Converter
接口,用于实现对于 String
==> LocalDateTime
的转换
public class LongToLocalDateTime implements Converter<Long, LocalDateTime> {
@Override
public LocalDateTime convert(Long str) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(str), ZoneId.systemDefault());
}
}
2、在 WebMvcConfigurer
注册新的 StringToLocalDate
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToLocalDateTime());
}
}
3、测试
END
以上只是简单的讲诉了 Spring 类型转换的使用方法,可以解决的具体问题;我后续将会学习关于 Spring 类型转换的相关组件的内容,可以关注后续文章
在此强烈推荐 [YourBatman 大佬的文章](#[YourBatman]-Spring类型转换 (qq.com))