编程语言
首页 > 编程语言> > java – spring-cloud-feign Client和带有Date类型的@RequestParam

java – spring-cloud-feign Client和带有Date类型的@RequestParam

作者:互联网

这次我正在使用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) {

正如您所看到的,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);
}

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

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 lib问题?

解决方法:

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

@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,spring,rest,jackson,netflix-feign
来源: https://codeday.me/bug/20190724/1525876.html