Web Development · Backend Frameworks
RestTemplate to RestClient Migration in Spring Boot 4.1
How to move from RestTemplate to RestClient on Spring Boot 4.1: side-by-side code, timeouts, error handling, @HttpExchange clients and test changes.
Abhishek Gupta
6 min read
Sponsored
Migrating from RestTemplate to RestClient on Spring Boot 4.1 is mostly a mechanical rewrite of call sites, plus three or four behavior differences you want to know about before you start. The Spring Framework reference says that as of 7.0, RestTemplate is deprecated in favor of RestClient and will be removed in a future version. Nothing stops working today. But every new deprecation warning in your build is a small tax, and the migration is cheap when done a class at a time.
Spring Boot 4.1.0 shipped on June 10, 2026, per the official announcement. If you are still weighing the Boot upgrade itself, the 4.1 release notes list the removals to check first. This guide covers the HTTP client side.
What the docs say about RestTemplate right now
The two official pages read slightly differently, and it helps to know why. The Spring Framework reference carries the deprecation notice and points to a “Migrating to RestClient” section. The Spring Boot reference is softer: it calls RestTemplate the classic way to call REST services and says you might keep it when you have existing code you do not want to migrate.
Boot also does not auto-configure a RestTemplate bean. It auto-configures a RestTemplateBuilder and RestTemplateCustomizer support. For new code, RestClient is the direction. For existing code, the Boot docs give you permission to move at your own pace.
Step 1: wrap what you already have
You do not need a big-bang rewrite. The framework reference shows the first step:
RestClient restClient = RestClient.create(restTemplate);
The new client shares the RestTemplate’s request factory and interceptors, so timeouts, TLS settings and auth headers carry over. Migrate one component, run its tests, merge, repeat. When the last call site is gone, delete the RestTemplate bean and move the setup into a RestClient.Builder.
Step 2: rewrite the call sites
Here is a typical RestTemplate service:
@Service
public class OrderClient {
private final RestTemplate restTemplate;
public OrderClient(RestTemplateBuilder builder) {
this.restTemplate = builder.rootUri("https://orders.example.com").build();
}
public Order find(long id) {
return restTemplate.getForObject("/orders/{id}", Order.class, id);
}
public void create(Order order) {
restTemplate.postForEntity("/orders", order, Void.class);
}
}
And the RestClient version, following the pattern in the Boot reference:
@Service
public class OrderClient {
private final RestClient restClient;
public OrderClient(RestClient.Builder builder) {
this.restClient = builder.baseUrl("https://orders.example.com").build();
}
public Order find(long id) {
return restClient.get()
.uri("/orders/{id}", id)
.retrieve()
.body(Order.class);
}
public void create(Order order) {
restClient.post()
.uri("/orders")
.contentType(MediaType.APPLICATION_JSON)
.body(order)
.retrieve()
.toBodilessEntity();
}
}
Two details to note. The builder method is baseUrl, not rootUri. And the chain needs a terminal operation (body, toEntity or toBodilessEntity). The docs are blunt: calling retrieve() alone has no effect, so a forgotten .toBodilessEntity() on a POST means the request never goes out. Review every void call site for this.
Where behavior differs
| Situation | RestTemplate | RestClient |
|---|---|---|
| 4xx and 5xx responses | Throws a RestClientException subclass | Same default, overridable per call with onStatus or per client with defaultStatusHandler |
| Custom handling | ResponseErrorHandler on the template | onStatus(...) handlers on the call |
| Raw response access | execute / exchange with callbacks | exchange((request, response) -> ...) |
| Status handlers with raw access | n/a | Not applied inside exchange() |
| Setup | RestTemplateBuilder | Prototype RestClient.Builder |
Error handling deserves the most review time. If you wrote a ResponseErrorHandler to turn a 404 into an empty result, move that logic to onStatus:
Order order = restClient.get()
.uri("/orders/{id}", id)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
throw new OrderLookupException(response.getStatusCode());
})
.body(Order.class);
If you drop down to exchange() for full control, remember that status handlers do not run there. You own the status check.
Timeouts, TLS and the builder trap
Spring Boot configures the injected RestClient.Builder with message converters and a request factory. Set shared defaults once, in configuration:
spring:
http:
clients:
connect-timeout: 2s
read-timeout: 1s
redirects: dont-follow
Note the key is spring.http.clients, plural. Release 4.1 also adds spring.http.clients.cookie-handling, and its Reactor-based request factory now applies system proxy properties by default, so check proxy behavior if you run on that factory.
Three traps from the Boot reference:
- The builder is a prototype bean and is stateful. Call
builder.clone()when you need several clients with different settings, or one client’sbaseUrlleaks into the next. RestClient.create()skips auto-configuration andRestClientCustomizerbeans entirely. In a Boot app, inject the builder instead.- For mutual TLS or a private CA, inject
RestClientSsland call.apply(ssl.fromBundle("mybundle")). Do not hand-roll anSSLContext.
Boot picks the underlying HTTP library in a fixed order: Apache HttpClient, Jetty, Reactor Netty, the JDK HttpClient, then HttpURLConnection. If you are surprised by which one you got, set spring.http.clients.imperative.factory explicitly.
Replace wrapper classes with @HttpExchange
If your OrderClient is mostly forwarding calls, you can declare an interface and let Spring generate the implementation:
@HttpExchange("/orders")
public interface OrderApi {
@GetExchange("/{id}")
Order find(@PathVariable long id);
@PostExchange
void create(@RequestBody Order order);
}
RestClient restClient = builder.baseUrl("https://orders.example.com").build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
OrderApi api = factory.createClient(OrderApi.class);
This is optional. It pays off when a service has many endpoints and little logic around them. For one or two calls, a plain RestClient is clearer.
Update the tests
Tests that mock RestTemplate need to change with the code. Spring Framework 7 adds RestTestClient, which wraps RestClient and exposes assertions on the response. It can run against a live server or, for Spring MVC apps, bind to MockMvc without one:
RestTestClient client = RestTestClient.bindToController(new OrderController()).build();
client.get().uri("/orders/1")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk();
For clients you call out to, test the real RestClient against a stub server and assert on the request, not on a mocked RestTemplate. Mocks of the old API will not survive the rewrite anyway.
A sensible order of work
- Build with deprecation warnings visible and count the
RestTemplateusages. - Pick the service with the most error-handling code and migrate it first, using
RestClient.create(restTemplate)as a bridge. - Move shared setup into
RestClient.Builderandspring.http.clients.*. - Migrate the rest, then delete the
RestTemplatebeans and theRestTemplateBuilderinjections.
If the upgrade is part of a larger version bump, the same one-step-at-a-time habit applies to other stacks. The Java 27 upgrade guide covers the runtime side of a JVM upgrade, the Go encoding/json v2 migration guide shows a bridge-then-replace approach in another language, and the Laravel 12 to 13 guide walks a framework upgrade in the same order.
The deprecation gives you a long runway. Spend it on the error handling and the tests, because the syntax change is the easy part.
Frequently asked questions
- Is RestTemplate removed in Spring Boot 4.1?
- No. The Spring Framework reference says RestTemplate is deprecated as of 7.0 and will be removed in a future version, but it still works. Spring Boot 4.1 still auto-configures a RestTemplateBuilder. Plan the move, but you have time.
- Should I use RestClient or WebClient?
- Use RestClient for blocking calls in servlet applications. The Spring Framework docs point to WebClient for asynchronous and streaming scenarios. Switching a blocking service to WebClient only to escape RestTemplate adds reactive types you probably do not need.
- Can I migrate gradually?
- Yes. RestClient.create(restTemplate) wraps an existing RestTemplate, so old and new code can share one configured request factory while you move components over one at a time.
Sources
Sponsored
More from this category
More from Web Development
Sponsored
Discussion
Join the conversation.
Comments are powered by GitHub Discussions. Sign in with your GitHub account to leave a comment.
Sponsored