はじめに
外部APIを呼ぶとき、RestClientでURLを組み立ててリクエストを送るコードを、APIごとに書いていませんか。Spring Boot 4では、呼び出したいAPIをJavaのインターフェースとして書くだけで、Springが実装を自動で作ってくれます。これがHTTP Service Clientです。
この記事では、HTTP Service Clientの書き方と、Spring Boot 4で増えた自動設定の使い方を整理します。
- 対象読者:Spring Bootのアプリから外部APIを呼んでいる方、OpenFeignを使っている方
- 前提バージョン:Spring Boot 4.0 / Java 25
- この記事で分かること:インターフェースの書き方、登録と設定、認証ヘッダーの付け方、テストのしかた
結論
- 外部APIを
@HttpExchangeを付けたインターフェースとして書くと、Springが実装を作る - Spring Boot 4では、
@ImportHttpServicesで登録し、spring.http.serviceclient.<グループ>.*で接続先ごとに設定できる - Spring Cloud OpenFeignを入れなくても、宣言的なHTTPクライアントを使える
これまでの書き方との違い
RestClientで直接書くと、次のようになります。
@Service
public class PaymentGateway {
private final RestClient restClient;
public PaymentGateway(RestClient.Builder builder) {
this.restClient = builder.baseUrl("https://api.payment.example.com").build();
}
public PaymentResult find(String id) {
return restClient.get()
.uri("/v1/payments/{id}", id)
.retrieve()
.body(PaymentResult.class);
}
}
呼び出すAPIが増えるほど、同じようなコードが並びます。HTTP Service Clientでは、これをインターフェースだけで表します。
インターフェースを書く
@HttpExchange("/v1/payments")
public interface PaymentClient {
@GetExchange("/{id}")
PaymentResult find(@PathVariable String id);
@PostExchange
PaymentResult pay(@RequestBody PaymentRequest request,
@RequestHeader("Idempotency-Key") String idempotencyKey);
@DeleteExchange("/{id}")
void cancel(@PathVariable String id);
}
Controllerの書き方とよく似ています。
| サーバー側(Controller) | クライアント側 |
|---|---|
| @RequestMapping | @HttpExchange |
| @GetMapping など | @GetExchange など |
| @PathVariable、@RequestBody など | 同じものを使う |
戻り値を ResponseEntity<PaymentResult> にすれば、ステータスコードやヘッダーも受け取れます。
インターフェースの書き方自体はSpring Framework 6(Spring Boot 3)からありました。Spring Boot 3では、インターフェースから実装を作る HttpServiceProxyFactory の設定を自分で書く必要がありましたが、Spring Boot 4ではそこが自動化されました。
登録と設定
インターフェースを登録する
@SpringBootApplication
@ImportHttpServices(group = "payment", types = PaymentClient.class)
@ImportHttpServices(group = "shipping", basePackages = "com.example.ec.client.shipping")
public class EcApplication {
public static void main(String[] args) {
SpringApplication.run(EcApplication.class, args);
}
}
-
typesで1つずつ、basePackagesでパッケージごとまとめて登録できる - 接続先ごとに「グループ」を分ける。グループを省略すると
defaultグループになる
接続先をプロパティで設定する
spring:
http:
clients: # 全グループ共通
connect-timeout: 3s
read-timeout: 5s
serviceclient:
payment: # グループごと
base-url: https://api.payment.example.com
read-timeout: 10s
shipping:
base-url: https://api.shipping.example.com
正式版より前の記事にある spring.http.client.service.group.* は古い名前なので、使わないようにします。
依存関係には spring-boot-starter-restclient が必要です。Spring Boot 4では、RestClientがWebのスターターに含まれなくなりました。
使う側
登録したインターフェースは、普通のBeanとして注入できます。
@Service
public class CheckoutService {
private final PaymentClient paymentClient;
public CheckoutService(PaymentClient paymentClient) {
this.paymentClient = paymentClient;
}
public PaymentResult checkout(PaymentRequest request) {
return paymentClient.pay(request, UUID.randomUUID().toString());
}
}
認証ヘッダーなどを付ける
グループ単位でRestClientの設定を変えたいときは、RestClientHttpServiceGroupConfigurer を使います。
@Bean
RestClientHttpServiceGroupConfigurer paymentAuth(PaymentTokenProvider tokens) {
return groups -> groups
.filterByName("payment")
.forEachClient((group, builder) -> builder
.requestInterceptor((request, body, execution) -> {
request.getHeaders().setBearerAuth(tokens.current());
return execution.execute(request, body);
}));
}
payment グループのリクエストにだけ、Bearerトークンが付きます。WebClientで動かすグループには、WebClientHttpServiceGroupConfigurer を使います。
リトライと組み合わせる
Spring Framework 7で本体に入った @Retryable と組み合わせると、一時的なエラーの再試行も簡単に書けます(設定クラスに @EnableResilientMethods が必要です)。
@Retryable(includes = PaymentTimeoutException.class, maxRetries = 3, delay = 200, multiplier = 2)
public PaymentResult checkout(PaymentRequest request) {
return paymentClient.pay(request, idempotencyKey(request));
}
決済のように二重に処理されると困るAPIでは、上の例のように冪等キー(Idempotency-Key)を付けてから再試行するのが安全です。
テストのしかた
サービス層のテストでは、インターフェースを @MockitoBean でモックにするだけで済みます。
@SpringBootTest
class CheckoutServiceTest {
@MockitoBean
PaymentClient paymentClient;
@Autowired
CheckoutService checkoutService;
@Test
void 決済できる() {
given(paymentClient.pay(any(), any())).willReturn(new PaymentResult("p-1", "PAID"));
assertThat(checkoutService.checkout(new PaymentRequest(1000)).status()).isEqualTo("PAID");
}
}
HTTPの中身まで確かめたいときは、WireMockなどでダミーのサーバーを立て、base-url をそちらに向けます。
OpenFeignとの比較
| 観点 | HTTP Service Client | Spring Cloud OpenFeign |
|---|---|---|
| 必要な依存 | Spring Bootのスターターだけ | Spring Cloud |
| 通信 | RestClient / WebClient | Feign独自 |
| 設定 | spring.http.* と同じ | Feign独自の設定 |
| 今後 | Spring本体の機能 | 機能追加は終了し保守のみ |
新しく作るなら、HTTP Service Clientを選ぶのが自然です。RestClientのタイムアウトやコネクションプールの設定も、そのまま効きます。
まとめ
- 外部APIを
@HttpExchangeのインターフェースとして書くと、Springが実装を作る - Spring Boot 4では
@ImportHttpServicesで登録し、spring.http.serviceclient.<グループ>.*で接続先ごとに設定する - 認証ヘッダーなどは
RestClientHttpServiceGroupConfigurerでグループ単位に設定する -
@Retryableと組み合わせると再試行も簡単。二重処理が困るAPIには冪等キーを付ける - テストでは、インターフェースを
@MockitoBeanでモックにするだけで済む - Spring Cloud OpenFeignなしで宣言的なクライアントが使える
関連記事
- Spring Boot 3と4は何が違うのか:比較表で押さえる世代の変化
- Spring Boot 3.5から4.0への移行:破壊的変更とチェックリスト
- RestClient / WebClientのタイムアウトとコネクションプール:デフォルト値のままでは本番に出せない
- Jackson 3移行ガイド:デフォルト値の変更でAPIの出力が変わる
- JSpecifyでnull安全:@Nullableがばらばらだった歴史とSpring 7
外部APIが増えてきたら、まずは1つをインターフェースに置き換えてみてください。呼び出し先の一覧がひと目で分かるようになります。