spring-cloud-feign Client和@RequestParam with Date type

pat*_*s91 3 java rest spring jackson netflix-feign

这次我正在使用Declarative REST Client,在一些Spring Boot App中使用Feign.

我想要实现的是调用我的一个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) {
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,API接受带有from和to params的调用,格式为 (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);
}
Run Code Online (Sandbox Code Playgroud)

一般来说,几乎是复制粘贴.现在在我的启动应用程序的某个地方,我使用它:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
ResponseEntity response = inboundACustomersClient.customersLastVisit(formatter.parse(formatter.format(from)),
        formatter.parse(formatter.format(to)));
Run Code Online (Sandbox Code Playgroud)

而且,我得到的回报是

嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型[java.lang.String]转换为类型[@ org.springframework.web.bind.annotation.RequestParam @ org.springframework.format.annotation.DateTimeFormat java.util.Date]的值为'Sun May 03 00:00:00 CEST 2015';

嵌套异常是java.lang.IllegalArgumentException:无法解析'Sun May 03 00:00:00 CEST 2015'

所以,问题是,我对请求做了什么错,它在发送到我的API之前没有解析为"仅限日期"的格式?或者它可能是一个纯粹的Feign lib问题?

Raf*_*ffa 8

您应该创建并注册一个假格式化程序来自定义日期格式

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)