Video in progress

How do you write an `@HttpExchange` interface client in Spring 6, and how is it different from OpenFeign?

I put @GetExchange and @PostExchange on an interface and proxy it through HttpServiceProxyFactory on top of a RestClient or WebClient. It looks like Feign, but it lives in Spring Framework itself and works without Spring Cloud; timeouts and tracing come from the underlying client.

📖 Answer

@HttpExchange("/api/customers")
public interface CustomerClient {

    @GetExchange("/{id}")
    CustomerDto get(@PathVariable long id);

    @PostExchange
    CustomerDto create(@RequestBody NewCustomer body);
}
@Configuration
class ClientConfig {
    @Bean
    CustomerClient customerClient(RestClient.Builder builder) {
        RestClient rest = builder.baseUrl("http://customer-service").build();
        return HttpServiceProxyFactory
                .builderFor(RestClientAdapter.create(rest))
                .build()
                .createClient(CustomerClient.class);
    }
}

RestClientAdapter exists since Spring 6.1; in 6.0 there was only WebClientAdapter.

Differences from Feign:

  • No extra dependency: spring-web is enough. With Feign you have to keep the Spring Cloud version in line with the Boot version.
  • Configuration is plain Java: timeouts, interceptors and the error handler are set on the RestClient.Builder (with defaultStatusHandler you turn 4xx/5xx into your own exceptions). In Feign there's its own world of Encoder, Decoder and ErrorDecoder.
  • If you build from the builder Boot provides, observation (tracing, metrics) is wired in automatically.
  • In Feign, discovery and load balancer integration through @FeignClient(name = ...) is ready out of the box. With @HttpExchange you wire that yourself with a @LoadBalanced builder.

In Spring Framework 7 (Boot 4), @ImportHttpServices cuts this boilerplate down further, but in Boot 3 the configuration above is the standard.