【发布时间】:2017-12-04 17:19:05
【问题描述】:
我正在尝试编写一个将 Java 8 Instant 作为请求参数的 Spring MVC GET 控制器:
@GetMapping
@JsonView(OrderListing.class)
@Validated
public WebSeekPaginatedResultsDto<OrderListingDto> findAll(@Valid OrderSearchCommand orderSearchCommand) {
// Some code
}
与:
public class OrderSearchCommand {
private Instant dateCreatedStart;
private Instant dateCreatedEnd;
// Some other fields
}
我正在从一些 React/Javascript 代码中触发一个 GET 请求:
http://localhost:8080/mms/front/orders?dateCreatedStart=2017-05-31T22%3A00%3A00.000Z
Spring 似乎不喜欢它并抛出错误。这是错误消息:
Failed to convert property value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart';
nested exception is java.lang.IllegalStateException:
Cannot convert value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart': no matching editors or conversion strategy found
知道我为什么会得到这个吗?
谢谢
【问题讨论】:
-
您收到的参数是
String类型,您正尝试将其存储在Instant中。您必须将String转换为Instant。 -
您必须使用
@DateTimeFormat注释字段,如duplicate link 所示。 -
如果
Instant不适用于“重复”帖子,请查看 spring 参考 (docs.spring.io/spring/docs/current/spring-framework-reference/…) 中的第 9.5 节。第 9.5.5 节介绍了自定义转换器的注册。 -
@Andreas 我重新提出了这个问题,因为我相信
@DateTimeFormat不适用于Instant。Instant未列在 Spring 4 参考文档中此注解支持的类型中。 -
@DwB 啊哈,我刚才看了
DateTimeFormat的javadoc,上面写着"JSR-310java.timetypes",你说的没错,源代码Jsr310DateTimeFormatAnnotationFormatterFactory只列出了 6 种类型:LocalDate、LocalTime、LocalDateTime、ZonedDateTime、OffsetDateTime、OffsetTime。
标签: java spring spring-mvc java-8 java.time.instant