Video in progress

Strong Middle 🧭 Design patterns

Why does Spring Boot provide `RestClient.Builder` as a bean, and what do you lose if you create a client with `RestClient.create()`?

Boot auto-configures the builder and, through customizers, adds message converters, observation (metrics and tracing) and your shared settings to it. The static RestClient.create() or RestClient.builder() bypasses all of that, so outgoing requests show up in neither metrics nor traces.

📖 Answer

This is a good example of the builder + customizer pattern. Boot declares the RestClient.Builder bean with prototype scope and applies every RestClientCustomizer in the context to it. You add only the part specific to you:

@Bean
RestClient paymentClient(RestClient.Builder builder, PaymentProps props) {
    return builder.baseUrl(props.url())
                  .defaultHeader("X-Api-Key", props.key())
                  .build();
}

A case I've seen in one service: someone wrote RestClient.create(url), Grafana had no http.client.requests metric for external calls, and the trace broke off at that service because the traceparent header never went to the next service. The cause was that the observation setup existed only on the auto-configured builder.

To add a shared setting to all clients, you write a customizer:

@Bean
RestClientCustomizer correlationId() {
    return b -> b.requestInterceptor(new CorrelationIdInterceptor());
}

There is one trap: the builder is mutable. Because it's a prototype, each injection point gets a fresh copy, but if you build two clients from one builder inside a single method, the first one's baseUrl and headers carry over to the second. In that case, use builder.clone().

WebClient.Builder works the same way; Boot provides it with WebClientCustomizers.