Sub topic 9
Interceptors and shared customization
This chapter assumes you can build a RestClient from the Spring Boot RestClient.Builder (see the chapter on creating a client). You should also be comfortable with lambdas and Spring bean configuration. By the end you will be able to add cross-cutting behavior such as authentication, logging and correlation headers. You will also know how to share that behavior across several clients.
Why cross-cutting behavior needs a home
Most API clients need the same small things on every request. Examples are an Authorization header, a correlation ID for tracing, request logging, and metrics. You could add these in each call:
restClient.get()
.uri("/todos/{id}", id)
.header("Authorization", "Bearer " + token)
.retrieve()
.body(Todo.class);This works, but it repeats the header in every method, and one forgotten call sends an unauthenticated request. RestClient offers three tools to avoid that:
- Default settings on the builder, such as
defaultHeader. - Request interceptors, which run code around every request.
- Customizers, which apply the same builder configuration to several clients.
Default headers versus interceptors
A default header is a fixed value set once on the builder:
RestClient client = RestClient.builder()
.baseUrl("https://api.example.com")
.defaultHeader("X-Client-Name", "todo-app")
.build();Use a default header when the value never changes while the client lives. Use an interceptor when the value must be computed per request, or when you need to inspect or replace the response. A token that expires is the classic case. A default header would keep sending the old value, while an interceptor can ask for a fresh one each time.
Request interceptors
A request interceptor implements ClientHttpRequestInterceptor. It has one method:
ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOExceptionThe parameters are:
requestis the outgoing request. You can change its headers.bodyis the request body as a byte array. It is already serialized.executionrepresents the rest of the chain. Callingexecution.execute(request, body)sends the request (or passes it to the next interceptor) and returns the response.
Because the interface has a single method, you can write it as a lambda. This example adds a bearer token to every request:
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 interceptor runs for every call made through this client, whatever the HTTP method.
How the chain executes
Interceptors form a chain. Each one decides whether to call execution.execute(...). The code before that call runs on the way out. The code after it runs on the way back, when the response is available.
Interceptors run in the order you register them on the way out, and in reverse order on the way back.
Registering several interceptors
Call requestInterceptor once per interceptor, or pass a list with requestInterceptors:
import java.util.UUID;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestClient;
class InterceptorExamples {
RestClient tracedClient(RestClient.Builder builder, String token) {
ClientHttpRequestInterceptor auth = (request, body, execution) -> {
request.getHeaders().setBearerAuth(token);
return execution.execute(request, body);
};
ClientHttpRequestInterceptor correlation = (request, body, execution) -> {
request.getHeaders().set("X-Correlation-Id", UUID.randomUUID().toString());
return execution.execute(request, body);
};
return builder
.baseUrl("https://api.example.com")
.requestInterceptor(auth)
.requestInterceptor(correlation)
.build();
}
}Here auth runs first, then correlation. Because the correlation ID is generated inside the lambda, every request gets a new value. A default header could not do that.
Reading the response in an interceptor
The code after execute sees the response. This interceptor logs the method, URI and status:
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
class LoggingInterceptor implements ClientHttpRequestInterceptor {
private static final Logger log = LoggerFactory.getLogger(LoggingInterceptor.class);
@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;
log.info("{} {} -> {} in {} ms",
request.getMethod(), request.getURI(), response.getStatusCode(), millis);
return response;
}
}Register it with .requestInterceptor(new LoggingInterceptor()).
Gotchas with interceptors
- Always call
execute, unless you mean to stop the request. If you forget to, the request is never sent. Returning your own response without callingexecuteis legal, but it is rarely what you want outside tests. - Do not read the response body unless you must. The body is a stream that can be read only once. If your interceptor consumes it, the later
body(...)call finds nothing left. Logging only the status and headers avoids this. If you need to log bodies, the request factory has to buffer them. Spring providesBufferingClientHttpRequestFactoryfor that, at the cost of holding every response in memory. See the chapter on request factories. - Interceptors see the serialized body. The
bodyargument is abyte[]. You cannot get the original Java object there. - Keep them fast and thread-safe. One
RestClientis shared by many threads, so the same interceptor instance handles concurrent requests. Keep per-request data in local variables, not in fields. - Error responses still reach the interceptor. A 404 or 500 is returned as a normal
ClientHttpResponse. The exception is raised later, inretrieve(), so your interceptor can log failures. Connection failures and timeouts, however, throw anIOExceptionfromexecute.
Handling a failing token
An interceptor can react to a response. This one refreshes a token once after a 401 and retries. The TokenProvider interface is a stand-in for your own code.
import java.io.IOException;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
interface TokenProvider {
String current();
String refresh();
}
class RefreshingAuthInterceptor implements ClientHttpRequestInterceptor {
private final TokenProvider tokens;
RefreshingAuthInterceptor(TokenProvider tokens) {
this.tokens = tokens;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().setBearerAuth(tokens.current());
ClientHttpResponse response = execution.execute(request, body);
if (response.getStatusCode().value() == HttpStatus.UNAUTHORIZED.value()) {
response.close();
request.getHeaders().setBearerAuth(tokens.refresh());
return execution.execute(request, body);
}
return response;
}
}Note response.close() before the retry. It releases the connection held by the first response. Retrying is safe here only because the request body is a byte[] that can be sent again. Be careful about retrying non-idempotent requests such as POST in your own code.
Customizing the builder in one place
With Spring Boot, RestClient.Builder is a prototype-scoped bean. Each injection point gets a fresh builder that already carries Boot's defaults, such as the configured message converters. So you can customize each client separately without affecting the others.
When several clients need the same setup, put it in a RestClientCustomizer. Boot applies every RestClientCustomizer bean to each builder it hands out:
import java.util.UUID;
import org.springframework.boot.web.client.RestClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class SharedRestClientConfig {
@Bean
RestClientCustomizer commonCustomizer() {
return builder -> builder
.defaultHeader("X-Client-Name", "todo-app")
.requestInterceptor((request, body, execution) -> {
request.getHeaders().set("X-Request-Id", UUID.randomUUID().toString());
return execution.execute(request, body);
});
}
}Every RestClient built from an injected RestClient.Builder now sends both headers. The todoRestClient bean from the earlier chapter needs no change.
Ordering and precedence
The customizers run before your own code touches the builder. Anything you set afterward can add to, or replace, what they set. For example, defaultHeader adds a value to the named header, while defaultHeaders(consumer) gives you the whole header map to change. If you need to replace a header from a customizer, use the second form:
RestClient client = builder
.defaultHeaders(headers -> headers.set("X-Client-Name", "billing-app"))
.build();When you have several customizer beans, add @Order to control which runs first. Keep customizers independent, so that they do not rely on running in a particular order.
Modifying a built client with mutate()
A built RestClient is immutable, but you can derive a new one from it. mutate() returns a builder initialized with the same settings:
RestClient adminClient = todoRestClient.mutate()
.defaultHeader("X-Role", "admin")
.build();The original client is unchanged. This is useful when a service needs one variant of a shared client, for example with an extra header.
Per-request customization
Not everything belongs on the client. For one-off changes, set the value on the request:
Todo todo = restClient.get()
.uri("/todos/{id}", id)
.header("If-None-Match", etag)
.retrieve()
.body(Todo.class);A rule of thumb for where to place a setting:
| Behavior | Best place |
|---|---|
| Fixed value for every call (accept type, client name) | `defaultHeader` on the builder |
| Value computed per call (token, correlation ID) | Request interceptor |
| Same setup for many clients | `RestClientCustomizer` bean |
| One variant of an existing client | `mutate()` |
| Value tied to one call (`If-None-Match`) | `.header(...)` on the request |
Common errors
- Customizer has no effect. Customizers apply only to builders that Boot supplies. If you call
RestClient.builder()orRestClient.create()yourself, they are skipped. InjectRestClient.Builderinstead. - Duplicated headers. Setting a header with
defaultHeaderin both a customizer and a client config sends two values. UsedefaultHeaders(consumer)withsetto replace. - Empty response body after logging. An interceptor read the response stream. Log only status and headers, or buffer the response.
- Token never refreshes. A token set once with
defaultHeaderis fixed for the life of the client. Move it into an interceptor. - Requests never complete. An interceptor returned without calling
execute, or called it and then blocked. Check each code path. - Interceptor order surprises. Auth must run before a logging interceptor if you want the logged request to show the header. Register in the order you want.
Summary of key points
- A
ClientHttpRequestInterceptorwraps every request. Code beforeexecution.executeruns outbound. Code after it runs on the response. - Interceptors are registered with
requestInterceptorand run in registration order. - The response body is a one-time stream, so avoid reading it in an interceptor.
- Boot injects a fresh
RestClient.Buildereach time and applies allRestClientCustomizerbeans to it. - Use
mutate()to derive a variant of an existing client.
Exercise
A team sets the bearer token with defaultHeader("Authorization", "Bearer " + token) when building the RestClient bean at startup. After an hour, calls start failing with 401 even though the token provider now returns a new token. What is the cause, and how would you fix it?
Show answer
defaultHeader stores the value once, when the builder runs, so the client keeps sending the original token. Replace it with a request interceptor that reads the current token on each request, for example requestInterceptor((request, body, execution) -> { request.getHeaders().setBearerAuth(tokens.current()); return execution.execute(request, body); }).
Exercise
You register a RestClientCustomizer bean that adds a logging interceptor, but a client created with RestClient.create("https://api.example.com") does not log anything. Why, and what change makes it log?
Show answer
Boot applies customizers only to the RestClient.Builder beans it provides. RestClient.create(...) does not use that builder. Inject RestClient.Builder into the configuration class and build the client from it, for example builder.baseUrl("https://api.example.com").build().
Exercise
A logging interceptor prints the response body by reading it from the ClientHttpResponse. Afterward, body(Todo.class) returns null. Explain why and give one way to avoid it.
Show answer
The response body is a stream that can be read only once. The interceptor consumed it, so the later conversion finds no data. Avoid it by logging only the status and headers, or by configuring the client with a BufferingClientHttpRequestFactory so the body can be read more than once.