2016-02-02 62 views
1

這次我正在使用Declarative REST Client,Feign在一些Spring Boot App中。spring-cloud-feign客戶端和帶日期類型的@RequestParam

我想達到什麼是叫我的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接受電話與和日期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))); 

而且,什麼我回來是

嵌套的例外是 org.springframework.core.convert.ConversionFailedException:無法 從類型[java.lang.String]轉換爲類型 [@ org.springframework.web.bind.annotation.RequestParam @ org.springframework.format.annotation.DateTimeFormat java.util.Date] for value'Sun May 03 00:00:00 CEST 2015';

嵌套的例外是java.lang.IllegalArgumentException異常:無法解析 「太陽05月03日00:00:00 CEST 2015年」

所以,問題是,我在做什麼毛病的要求,即在發送到我的API之前它不解析爲「僅限日期」格式?或者,也許這是一個純粹的Feign lib問題?

回答

4

您應該創建並註冊一個假死格式自定義數據格式

@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()); 
    } 
} 
+0

解決方案的作品真的很好。也許一些額外的信息會有用。通過實現feign-client解決方案,您不需要Feign界面中的DateTimeFormat批註。 –

0

另一種簡單的解決方案是使用默認的接口方法的日期爲字符串轉換像

@RequestMapping(value = "/path", method = GET) 
List<Entity> byDate(@RequestParam("date") String date); 

default List<Entity> date(Date date) { 
    return date(new SimpleDateFormat("dd.MM.yyyy").format(validityDate)); 
}