spring-cloud-feign Client and @RequestParam with Date type
You should create and register a feign formatter to customize the date format
@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());
}
}
patrykos91
Java Spring Web Developer New tech. enthusiast. Board and PC games enthusiast, addicted from Marvel/DC movies and tv shows.
Updated on June 17, 2022Comments
-
patrykos91 almost 2 years
This time I was working with Declarative REST Client, Feign in some Spring Boot App.
What I wanted to achieve is to call one of my REST API's, which looks like:
@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) {
As You can see, the API accepts calls with from and to Date params formatted like
(yyyy-MM-dd)
In order to call that API, I've prepared following piece of
@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); }
Generally, almost copy-paste. And now somewhere in my boot App, I use that:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); ResponseEntity response = inboundACustomersClient.customersLastVisit(formatter.parse(formatter.format(from)), formatter.parse(formatter.format(to)));
And, what I get back is that
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'
So, the question is, what am I doing wrong with request, that it doesn't parse to "date-only" format before sending to my API? Or maybe it is a pure Feign lib problem?