🌐 HTTP Interface Clients: The Declarative Replacement for RestTemplate
RestTemplate is deprecated. Feign is heavy. Spring's @HttpExchange (backed by HttpServiceProxyFactory) is the modern, compile-time safe, AOT-friendly way to call external APIs.
📝 The Interface-Driven Approach
@HttpExchange(url = "/api/v1/orders")
public interface OrderClient {
@GetExchange("/{id}")
OrderDto getOrder(@PathVariable String id);
@PostExchange
@ResponseStatus(HttpStatus.CREATED)
OrderDto createOrder(@RequestBody CreateOrderRequest request);
}
@Configuration
public class ClientConfig {
@Bean
OrderClient orderClient(WebClient.Builder webClientBuilder) {
var baseUrl = "https://orders.example.com";
var client = webClientBuilder.baseUrl(baseUrl).build();
return HttpServiceProxyFactory.builderFor(WebClientAdapter.create(client))
.build().createClient(OrderClient.class);
}
}
🔍 Why It Matters in Production
- Compile-time contract validation (no more typo'd paths)
- Automatic JSON serialization via Jackson
- Seamless error mapping with
@ExceptionHandlerorProblemDetail - Native AOT safe (no runtime reflection tricks)
🚀 Migration Tip
Don't rewrite everything at once. Use HttpServiceProxyFactory alongside RestTemplate during transition. Wire interceptors for auth, retries, and correlation IDs exactly like you would with WebClient. The only difference? You write less glue code.
Tags:
Spring Framework