Sub topic 9
Interceptors and shared customization
This chapter covers how to apply behavior to every request a RestClient sends. It assumes you can already build a RestClient from the Spring Boot RestClient.Builder, as shown in the chapter on creating a client. You should also be comfortable with lambdas and Spring beans.
Why shared behavior matters
Some work belongs to every call, not to one endpoint. Examples are an Authorization header, a correlation ID, or request logging. Repeating that code at each call site invites mistakes. RestClient gives you two places to put it:
- A request interceptor runs for each request just before it is sent.
- A builder customization changes how the builder is configured, so every client built from it shares the change.
Request interceptors
A request interceptor is an implementation of ClientHttpRequestInterceptor. It receives the outgoing request, the request body as a byte array, and an execution object. Calling execution.execute(request, body) passes the request on to the next interceptor, or to the server if none remain. The call returns the response.
The simplest use is adding a bearer token:
RestClient authenticatedClient(RestClient.Builder builder, String token) {
return builder
.baseUrl("https://api.example.com")
.requestInterceptor((request, body, execution) -> {
request.getHeaders().setBearerAuth(token);
return execution.execute(request, body);
})
.build();
}The lambda changes the headers, then calls execute. Every request from this client now carries the token.
An interceptor can also act on the response. Because execute returns it, you can time the call or log the status:
import java.io.IOException;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
class TimingInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
long start = System.nanoTime();
ClientHttpResponse response = execution.execute(request, body);
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(request.getMethod() + " " + request.getURI()
+ " -> " + response.getStatusCode() + " in " + millis + " ms");
return response;
}
}Register it with requestInterceptor(new TimingInterceptor()).
Order and common errors
Interceptors run in the order you register them. The first one registered sees the request first and the response last.
Watch for these mistakes:
- Forgetting to call
execute. The request is never sent, and the caller gets no response. - Reading the response body inside the interceptor. The body stream can usually be read only once. If you consume it for logging,
body()later fails or returns nothing. Log the status and headers, or wrap the response in a buffering one. - Capturing a token that expires. A string captured in the lambda stays fixed. For short-lived tokens, call a supplier inside the lambda so each request gets the current value.
Shared customization with the builder
Spring Boot injects a RestClient.Builder that is a prototype bean. Each injection point gets a fresh copy, so configuring one client does not alter another.
Boot also applies any RestClientCustomizer beans to that builder. Use a customizer for settings that every client in the application should share:
import org.springframework.boot.web.client.RestClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
@Configuration
class SharedClientConfig {
@Bean
RestClientCustomizer commonHeaders() {
return builder -> builder
.defaultHeader(HttpHeaders.USER_AGENT, "todo-app/1.0")
.requestInterceptor(new TimingInterceptor());
}
}Every RestClient.Builder the application injects now starts with the user agent and the timing interceptor already set.
For a single client, you can derive a variant from an existing one. mutate() returns a builder initialized with the client's current settings:
RestClient adminClient(RestClient todoRestClient, String adminToken) {
return todoRestClient.mutate()
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + adminToken)
.build();
}The original client is unchanged.
Choosing between the options
| Need | Use |
|---|---|
| Behavior for one client only | `requestInterceptor` on that client's builder |
| Behavior for all clients in the app | A `RestClientCustomizer` bean |
| A variant of an existing client | `mutate()` |
Exercise
A teammate logs each response body inside an interceptor, and afterward body(Todo.class) returns nothing. What is the likely cause, and what could they log instead?
Show answer
The interceptor consumed the response body stream, which can usually be read only once. They should log only the status code and headers, or wrap the response in a buffering implementation so the body can be read again.
Exercise
Why does a RestClientCustomizer bean not affect a client created with RestClient.create()?
Show answer
Spring Boot applies customizers only to the RestClient.Builder bean it auto-configures. RestClient.create() builds its own builder outside Spring's control, so no customizers are applied.