6

今回は、Declarative REST Client, Feign in some Spring Boot App を使用しました。

私が達成したかったのは、次のような REST API の 1 つを呼び出すことです。

@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 Date パラメータを使用した呼び出しを受け入れます。(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: Unable to parse 'Sun May 03 00:00:00 CEST 2015' です

それで、問題は、APIに送信する前に「日付のみ」の形式に解析されないリクエストの何が間違っているのですか? それとも、純粋な Feign lib の問題でしょうか?

4

5 に答える 5

9

日付形式をカスタマイズするには、偽のフォーマッタを作成して登録する必要があります

@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());
    }
}
于 2016-04-06T14:44:55.310 に答える
1

偽のクライアントは現在 (2020 年 12 月)、上記の元の質問の構文とjava.time.LocalDateパラメーターとして a を使用して正常に動作します。つまり、次を使用できます。

  @FeignClient(name = "YOUR-SERVICE")
  interface ClientSpec {
    @RequestMapping(value = "/api/something", method = RequestMethod.GET)
    String doSomething(
        @RequestParam("startDate") 
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 
        LocalDate startDate);
  }
于 2020-12-16T17:24:15.903 に答える