Sub topic 5
RestClient and Spring Boot's RestClient.Builder
This chapter assumes you know Java 17 records, Spring beans and constructor injection, and basic HTTP (methods, status codes, headers, JSON). It also assumes you have read the chapters on @HttpExchange interfaces. Those interfaces only describe an API. RestClient makes the actual HTTP calls, so you need to know how it behaves and how Spring Boot configures it.
What RestClient is
RestClient is a synchronous HTTP client added in Spring Framework 6.1. It has a fluent API like WebClient, but it blocks the calling thread like RestTemplate. It does not need the reactive stack.
A RestClient handles several things for you:
- It builds the URI, including template variables and query parameters.
- It sends the request through a
ClientHttpRequestFactory, which wraps a concrete HTTP library. - It converts request and response bodies with
HttpMessageConverterinstances, so JSON becomes Java objects through Jackson. - It applies default headers and status handlers.
HttpServiceProxyFactory does not talk to the network itself. It turns each interface method call into a request description and hands it to an adapter. RestClientAdapter forwards that description to a RestClient. Everything the proxy does at runtime, including serialization, timeouts, authentication, and error behavior, comes from the RestClient you give it.
Calling the API without an interface
It helps to see the fluent API once, because the interface methods map onto it directly.
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
record Todo(Long id, Long userId, String title, boolean completed) {}
@Service
class TodoLookup {
private final RestClient restClient;
TodoLookup(RestClient.Builder builder) {
this.restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
}
Todo get(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}
List<Todo> listByUser(long userId) {
return restClient.get()
.uri(uri -> uri.path("/todos").queryParam("userId", userId).build())
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>() {});
}
}The Todo record here is the same one used by the TodoClient interface. Define it once in your project.
Each call follows the same steps:
- Choose a method with
get(),post(),put(),patch(), ordelete(). - Set the target with
uri(...). - Optionally add headers or a body.
- Call
retrieve(). - Read the result with
body(...)ortoEntity(...).
Generic types such as List<Todo> need a ParameterizedTypeReference, because Java erases the type argument at runtime. A proxy gets this information from the method's generic return type, so you don't write the reference yourself there.
The retrieve() step is the simple path. By default it throws an exception for any 4xx or 5xx response. If you need full control over the response, exchange(...) is available. The proxy uses retrieve()-style behavior, so the default error rule carries over to your interface methods.
The auto-configured RestClient.Builder
Spring Boot does not create a ready-made RestClient bean. It creates a RestClient.Builder bean, through RestClientAutoConfiguration. This is the fact to remember from this chapter. The reason is that every client you build needs its own base URL, headers, and authentication. A shared singleton RestClient would force all of them to share settings.
Three properties of this builder matter in practice.
It is prototype-scoped. Every injection point gets a fresh builder instance. Calling baseUrl(...) in one class does not change what another class receives. This is why the configuration class in the earlier example can set its own base URL without side effects.
It is pre-configured. The builder Boot hands you already contains:
- The same
HttpMessageConverterset Spring MVC uses, with your JacksonObjectMappersettings. If your application renames fields globally or registers a custom module, the client honors it. - A
ClientHttpRequestFactorythat Boot selects from what is on the classpath. It prefers Apache HttpComponents, then Jetty, then the JDKHttpClient, then the simple JDK connection. Settings underspring.http.client.*(connect and read timeouts, redirect behavior) apply to that factory. - Any
RestClientCustomizerbeans you have defined. - Observation support, so Micrometer can record client request metrics when it is on the classpath.
It is a builder, not a client. Calling build() produces an immutable RestClient. To derive a variation later, use restClient.mutate(), which returns a builder copy of the existing client.
Applying settings to every client with a customizer
If every client needs the same setting, such as a User-Agent header, put it in a RestClientCustomizer bean. Boot applies all customizers to every auto-configured builder before you receive it.
import org.springframework.boot.web.client.RestClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class RestClientDefaults {
@Bean
RestClientCustomizer userAgentCustomizer() {
return builder -> builder.defaultHeader("User-Agent", "todo-app/1.0");
}
}Customizers run before your own code touches the builder. Anything you set in your configuration class, such as a different User-Agent for one client, overrides the customizer value for that client.
Common errors
Using RestClient.builder() instead of the injected builder. The static method returns a plain builder with Spring Framework's defaults. It skips Boot's customizers, your ObjectMapper configuration, and the spring.http.client.* timeout properties. The client still works, so the problem shows up later, for example as a JSON field that fails to deserialize because the global Jackson settings were never applied. In application code, inject RestClient.Builder. Use the static method in unit tests where you want a clean builder.
Defining your own singleton RestClient.Builder bean. Boot's builder is conditional. If you declare a builder bean of your own, auto-configuration backs off, and you lose the shared setup. Every client then also shares that one mutable instance, so a baseUrl(...) call in one place leaks into another. If you need a custom builder, expose a customizer instead.
Forgetting that retrieve() throws. A 404 does not give you a null body. It throws HttpClientErrorException.NotFound. The error handling chapter covers custom handlers.
Expecting a RestClient bean. Injecting RestClient directly fails with a missing bean error unless you define one. Inject the builder and call build().
Reusing a builder after build() for a different purpose. The builder keeps its state. Calling baseUrl(...) again on the same instance and building a second client works, but it is easy to carry over headers by accident. Take a fresh builder per client, which the prototype scope gives you at each injection point.
How this connects to the proxy
Once you have a built RestClient, you pass it to RestClientAdapter.create(restClient). The adapter implements the HttpExchangeAdapter contract that HttpServiceProxyFactory expects. The next chapter covers that factory in detail. For now, remember that RestClient settings decide how every proxied call behaves.
Exercise
A teammate writes RestClient restClient = RestClient.builder().baseUrl("https://api.example.com").build(); inside a Spring Boot service. The application sets a global Jackson naming strategy and a read timeout under spring.http.client.read-timeout. Requests to the API now ignore both. What is the cause, and how do you fix it?
Show answer
The static RestClient.builder() creates a plain builder that bypasses Spring Boot's auto-configuration, so it does not get Boot's message converters (which carry the Jackson settings), customizers, or the configured request factory (which carries the timeout). The fix is to inject RestClient.Builder through the constructor, which Boot supplies pre-configured, and call baseUrl(...) and build() on that.
Exercise
Why does Spring Boot expose a prototype-scoped RestClient.Builder instead of a singleton RestClient bean?
Show answer
Each client usually needs its own base URL, default headers, and authentication. A prototype builder gives every injection point a fresh instance, so settings applied for one client do not leak into another, while Boot's shared configuration (converters, request factory, customizers) is still applied to each.