这次我使用声明式 REST 客户端,在一些 Spring Boot 应用程序中进行假装。
我想要实现的是调用我的 REST API 之一,如下所示:
@RequestMapping(value = "/customerslastvisit", method = RequestMethod.GET)
public ResponseEntity customersLastVisit(
@RequestParam(value = "from", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date from,
@RequestParam(value = "to", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date to) {
如您所见,API 接受格式为 (yyyy-MM-dd)
为了调用该 API,我准备了以下一段 @FeignClient
:
@FeignClient("MIIA-A")
public interface InboundACustomersClient {
@RequestMapping(method = RequestMethod.GET, value = "/customerslastvisit")
ResponseEntity customersLastVisit(
@RequestParam(value = "from", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date from,
@RequestParam(value = "to", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date to);
}
一般来说,几乎是复制粘贴。现在在我的启动应用程序的某个地方,我使用它:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
ResponseEntity response = inboundACustomersClient.customersLastVisit(formatter.parse(formatter.format(from)),
formatter.parse(formatter.format(to)));
然后,我得到的是
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value 'Sun May 03 00:00:00 CEST 2015';
nested exception is java.lang.IllegalArgumentException: Unable to parse 'Sun May 03 00:00:00 CEST 2015'
所以,问题是,我对请求做错了什么,它在发送到我的 API 之前没有解析为“仅限日期”格式?或者这可能是一个纯粹的 Feign 库问题?
最佳答案
您应该创建并注册一个假格式化程序来自定义日期格式
@Component
public class DateFormatter implements Formatter<Date> {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
@Override
public Date parse(String text, Locale locale) throws ParseException {
return formatter.parse(text);
}
@Override
public String print(Date date, Locale locale) {
return formatter.format(date);
}
}
@Configuration
public class FeignFormatterRegister implements FeignFormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addFormatter(new DateFormatter());
}
}
关于java - 带有 Date 类型的 spring-cloud-feign Client 和 @RequestParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35158065/