The Complete Guide to RestClient in Spring Boot 3.2 with Java 21 Virtual Threads
Part of the series “Java 21 & Spring Boot” · part 5 of 5
- Immutability in Java 21: Records, Defensive Copying, and Collections
- Modern Spring Boot with Java 21 — Virtual Threads, ScopedValue, and Structured Concurrency
- Java Virtual Threads Are a Bigger Deal Than You Think
- Spring Boot + JPA + Virtual Threads (Java 21): Avoid N+1, OSIV & Pagination Pitfalls
- The Complete Guide to RestClient in Spring Boot 3.2 with Java 21 Virtual Threads
On this page

RestClient in Spring Boot 3.2 with Java 21 Virtual Threads
Introduction
If you have been writing Java for any length of time, you have almost certainly used RestTemplate. It is familiar, well-documented, and it works. But Spring marked it as being in maintenance mode back in 2019, and with Java 21 and Spring Boot 3.2 now stable, there is a genuinely better option available.
This guide show you the full landscape of HTTP client options, explain exactly why RestClient paired with virtual threads is the right choice for new Spring Boot 3.2 projects, and give you production-grade code with a complete three-layer JUnit 5 test suite you can use immediately.
🎯 What you will learn
- Which HTTP client to use for Java 21 and why
- How to configure RestClient as a Spring bean
- All CRUD operations with proper error handling
- Three layers of JUnit 5 tests: Mockito unit tests, MockMvc web layer tests, WireMock integration tests
- Ten production best practices with explanations
1. The Java HTTP Client Landscape in 2024
Before writing a single line of code, it is worth understanding every realistic option and the trade-offs each one makes. There are six choices you will encounter in modern Java projects.

At a glace
1.1 RestTemplate — the old faithful
RestTemplate has been the default Spring HTTP client since 2009. Synchronous, imperative, and easy to understand. The problem is that Spring has explicitly put it in maintenance mode — it receives bug fixes but no new features. If you are starting a new project today, do not use it.
Spring will not remove RestTemplate, so existing code is safe. But for all new development on Spring Boot 3.2+, migrate to RestClient. The APIs are similar enough that migration is straightforward.
1.2 WebClient — the reactive option
WebClient is Spring’s reactive, non-blocking HTTP client built on Project Reactor. It is the right choice when you are building a fully reactive application with WebFlux. However, in a virtual thread application you are solving the same concurrency problem differently — virtual threads give you the scalability of reactive without the complexity. Mixing the two approaches adds overhead with no benefit.
1.3 java.net.http.HttpClient — the built-in option
Since Java 11 the JDK ships its own HTTP client. It supports HTTP/2, async calls, and works well with virtual threads. The downside in a Spring Boot project is that you lose Spring’s auto-configuration, message converters, interceptors, and observability integration. RestClient uses the JDK HttpClient internally in Spring Boot 3.2, so you get all the JDK benefits plus the Spring ecosystem on top.
1.4 OkHttp — the non-Spring favourite
OkHttp by Square is an excellent library, popular in Android and non-Spring Java projects. Great connection pooling, a clean interceptor model, and first-class HTTP/2 support. If you are not using Spring, OkHttp is a top pick. In a Spring Boot project it adds a dependency you do not need.
1.5 OpenFeign — the declarative approach
OpenFeign lets you define HTTP clients as annotated Java interfaces — no implementation code at all. It is a great fit for microservice architectures where you are calling many internal services. The trade-off is less direct control over request construction and a slightly higher learning curve for advanced scenarios like streaming or custom error handling.
1.6 RestClient — the winner for Spring Boot 3.2 + Java 21
RestClient was introduced in Spring Framework 6.1 (Spring Boot 3.2) as the modern synchronous HTTP client. It has a fluent API similar to WebClient, uses the JDK HttpClient under the hood, integrates with all of Spring’s auto-configuration, and pairs perfectly with virtual threads.
✅ Why RestClient wins for this stack
Spring Boot auto-configures RestClient.Builder with Micrometer metrics, distributed tracing, and observability out of the box. You write simple blocking code. Virtual threads handle concurrency. No reactive complexity needed.
2. Project Setup
2.1 Maven dependencies
RestClient ships with spring-boot-starter-web — you need zero additional dependencies. WireMock is added for integration tests only.
<!-- pom.xml -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version> <!-- Spring Boot 3.2+ required -->
</parent>
<properties>
<java.version>21</java.version> <!-- Java 21 for virtual threads -->
</properties>
<dependencies>
<!-- RestClient ships inside starter-web — no extra dependency needed -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Bean Validation for request DTOs -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- JUnit 5 + Mockito + MockMvc are all included in starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- WireMock: real HTTP stub server for integration tests -->
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>3.3.1</version>
<scope>test</scope>
</dependency>
</dependencies>
2.2 Enable virtual threads (one line)
This single property makes Tomcat handle every incoming HTTP request on a virtual thread. Spring Boot 3.2 wires everything else automatically.
# application.properties
# Makes Tomcat use a virtual thread for every incoming request.
spring.threads.virtual.enabled=true
app.api.base-url=https://jsonplaceholder.typicode.com
app.api.connect-timeout-seconds=3
app.api.read-timeout-seconds=10
2.3 Models as Java 21 records
Java 21 records are immutable, concise, and work natively with Jackson serialisation. Use them for all DTOs.
// Post.java
public record Post(
Long id,
Long userId,
String title,
String body
) {}
// CreatePostRequest.java — @NotBlank / @NotNull from Jakarta Validation
// @Valid in the controller activates these before the service is called
public record CreatePostRequest(
@NotNull Long userId,
@NotBlank String title,
@NotBlank String body
) {}
3. RestClient Configuration
Never create a RestClient inline in a service class. Always define a @Bean. This centralises your base URL, timeouts, headers, and error handling in one place — and makes test overrides trivial.
// RestClientConfig.java
@Configuration
public class RestClientConfig {
@Value("${app.api.base-url}")
private String baseUrl;
// WHY inject RestClient.Builder, not RestClient directly?
// Spring Boot auto-configures Builder with Micrometer metrics,
// distributed tracing, and observability. Building from the
// auto-configured Builder preserves all of that for free.
@Bean
public RestClient restClient(RestClient.Builder builder) {
return builder
.baseUrl(baseUrl)
.defaultHeader("Accept", "application/json")
.defaultHeader("Content-Type", "application/json")
// Map 4xx -> domain exceptions.
// Without this, RestClient throws a generic
// RestClientResponseException — hard to handle cleanly.
.defaultStatusHandler(
HttpStatusCode::is4xxClientError,
(request, response) -> {
if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new PostNotFoundException(-1L);
}
throw new ApiException(
response.getStatusCode().value(),
"Client error: " + response.getStatusCode()
);
}
)
// Map 5xx -> ApiException
.defaultStatusHandler(
HttpStatusCode::is5xxServerError,
(request, response) -> {
throw new ApiException(
response.getStatusCode().value(),
"Server error: " + response.getStatusCode()
);
}
)
.build();
}
}
4. PostService — All CRUD Operations Explained
Here is the complete service class with every HTTP verb, a query parameter example, and comments explaining each design decision. Notice that every method is completely synchronous — that is intentional and correct with virtual threads.
@Service
public class PostService {
private final RestClient restClient;
// Constructor injection makes unit testing trivial
public PostService(RestClient restClient) {
this.restClient = restClient;
}
// ── GET all ───────────────────────────────────────────────
// ParameterizedTypeReference is required for generics (List<Post>).
// Without it, type erasure causes Jackson to return
// List<LinkedHashMap> instead of List<Post> at runtime.
public List<Post> getAllPosts() {
return restClient.get()
.uri("/posts")
.retrieve()
.body(new ParameterizedTypeReference<List<Post>>() {});
}
// ── GET by id ─────────────────────────────────────────────
// {id} is a URI template variable — substituted safely by varargs.
// 404 -> PostNotFoundException (handled by RestClientConfig).
public Post getPostById(Long id) {
return restClient.get()
.uri("/posts/{id}", id)
.retrieve()
.body(Post.class);
}
// ── POST (create) ─────────────────────────────────────────
// .body(request) serialises the Java 21 record -> JSON via Jackson.
// .body(Post.class) deserialises the JSON response -> Post record.
public Post createPost(CreatePostRequest request) {
return restClient.post()
.uri("/posts")
.body(request)
.retrieve()
.body(Post.class);
}
// ── PUT (full update) ─────────────────────────────────────
public Post updatePost(Long id, CreatePostRequest request) {
return restClient.put()
.uri("/posts/{id}", id)
.body(request)
.retrieve()
.body(Post.class);
}
// ── DELETE ────────────────────────────────────────────────
// .toBodilessEntity() avoids NullPointerException when the
// response body is empty (which DELETE responses typically are).
public void deletePost(Long id) {
restClient.delete()
.uri("/posts/{id}", id)
.retrieve()
.toBodilessEntity();
}
// ── GET with query parameters ─────────────────────────────
// Always use the URI builder lambda for dynamic query params.
// NEVER concatenate: .uri("/posts?userId=" + userId)
// The lambda handles URL encoding and is safe from injection.
public List<Post> getPostsByUser(Long userId) {
return restClient.get()
.uri(uriBuilder -> uriBuilder
.path("/posts")
.queryParam("userId", userId)
.build())
.retrieve()
.body(new ParameterizedTypeReference<List<Post>>() {});
}
}
5.1 PostController
The controller stays clean because all HTTP concerns live here and all business logic lives in the service. The @Valid annotation activates Bean Validation on request bodies — invalid payloads are rejected before the service is ever called.
@RestController
@RequestMapping("/api/posts")
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@GetMapping
public List<Post> getAllPosts() {
return postService.getAllPosts();
}
@GetMapping("/{id}")
public Post getPostById(@PathVariable Long id) {
return postService.getPostById(id);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Post createPost(@Valid @RequestBody CreatePostRequest request) {
return postService.createPost(request);
}
@PutMapping("/{id}")
public Post updatePost(@PathVariable Long id,
@Valid @RequestBody CreatePostRequest request) {
return postService.updatePost(id, request);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deletePost(@PathVariable Long id) {
postService.deletePost(id);
}
}
5.2 Global exception handler with ProblemDetail
Spring 6 supports RFC 7807 ProblemDetail natively. Structured error responses with no custom DTO classes.
@RestControllerAdvice
public class GlobalExceptionHandler {
// PostNotFoundException -> 404 with detail message
@ExceptionHandler(PostNotFoundException.class)
public ProblemDetail handlePostNotFound(PostNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage()
);
}
// ApiException -> 502 (upstream 5xx) or 422 (upstream 4xx)
@ExceptionHandler(ApiException.class)
public ProblemDetail handleApiException(ApiException ex) {
HttpStatus status = ex.getStatusCode() >= 500
? HttpStatus.BAD_GATEWAY
: HttpStatus.UNPROCESSABLE_ENTITY;
return ProblemDetail.forStatusAndDetail(status, ex.getMessage());
}
}
6. Testing — The Three-Layer Strategy
A robust test suite for a RestClient-based service needs three distinct layers. Each layer catches different categories of bugs. Skipping any one of them leaves a gap.
Layer 1 — Unit tests with Mockito (@ExtendWith(MockitoExtension.class))
No Spring context. No network. Tests run in ~50ms. These verify service business logic and exception mapping in complete isolation.
The tricky part with RestClient unit tests is its fluent chain: restClient.get().uri(…).retrieve().body(…). Each method returns a different interface, so you need a separate mock for each step.
// PostServiceTest.java
@ExtendWith(MockitoExtension.class)
class PostServiceTest {
// One mock per step in the fluent chain
@Mock private RestClient restClient;
@Mock private RestClient.RequestHeadersUriSpec<?> headersUriSpec;
@Mock private RestClient.RequestHeadersSpec<?> headersSpec;
@Mock private RestClient.ResponseSpec responseSpec;
@Mock private RestClient.RequestBodyUriSpec bodyUriSpec;
@Mock private RestClient.RequestBodySpec bodySpec;
private PostService postService;
@BeforeEach
void setUp() { postService = new PostService(restClient); }
// ── GET by id: success path ───────────────────────────────
@Test
@DisplayName("getPostById returns post when found")
void getPostById_returnsPost() {
Post fake = new Post(1L, 1L, "Hello", "World");
doReturn(headersUriSpec).when(restClient).get();
doReturn(headersSpec).when(headersUriSpec).uri(eq("/posts/{id}"), any(Long.class));
doReturn(responseSpec).when(headersSpec).retrieve();
doReturn(fake).when(responseSpec).body(Post.class);
Post result = postService.getPostById(1L);
// AssertJ — fluent, readable, IDE-friendly
assertThat(result.id()).isEqualTo(1L);
assertThat(result.title()).isEqualTo("Hello");
}
// ── GET by id: 404 path ───────────────────────────────────
@Test
@DisplayName("getPostById propagates PostNotFoundException on 404")
void getPostById_throwsNotFound() {
doReturn(headersUriSpec).when(restClient).get();
doReturn(headersSpec).when(headersUriSpec).uri(eq("/posts/{id}"), any(Long.class));
doReturn(responseSpec).when(headersSpec).retrieve();
when(responseSpec.body(Post.class)).thenThrow(new PostNotFoundException(999L));
// assertThatThrownBy lets you assert both type AND message
assertThatThrownBy(() -> postService.getPostById(999L))
.isInstanceOf(PostNotFoundException.class)
.hasMessageContaining("999");
}
// ── POST: create ──────────────────────────────────────────
@Test
@DisplayName("createPost sends body and returns created post")
void createPost_sendsBodyAndReturns() {
CreatePostRequest req = new CreatePostRequest(1L, "Title", "Body");
Post created = new Post(101L, 1L, "Title", "Body");
doReturn(bodyUriSpec).when(restClient).post();
doReturn(bodySpec).when(bodyUriSpec).uri("/posts");
doReturn(bodySpec).when(bodySpec).body(req);
doReturn(responseSpec).when(bodySpec).retrieve();
doReturn(created).when(responseSpec).body(Post.class);
Post result = postService.createPost(req);
assertThat(result.id()).isEqualTo(101L);
verify(bodySpec).body(req); // confirm body was actually set
}
}
Layer 2 — Web layer tests with MockMvc (@WebMvcTest)
Loads only the controller layer. No service beans, no RestClient, no network. Runs in ~500ms. Catches HTTP routing, Bean Validation, JSON serialisation, and exception-to-status-code mapping.
// PostControllerTest.java
@WebMvcTest(PostController.class) // loads ONLY the web layer
class PostControllerTest {
@Autowired MockMvc mockMvc;
@Autowired ObjectMapper objectMapper;
@MockBean PostService postService; // replace real service with mock
@Test
@DisplayName("GET /api/posts returns 200 with post list")
void getAllPosts_returns200() throws Exception {
when(postService.getAllPosts()).thenReturn(
List.of(new Post(1L, 1L, "Title", "Body"))
);
mockMvc.perform(get("/api/posts")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$[0].title").value("Title"));
}
@Test
@DisplayName("GET /api/posts/999 returns 404 ProblemDetail")
void getPostById_returns404() throws Exception {
when(postService.getPostById(999L))
.thenThrow(new PostNotFoundException(999L));
mockMvc.perform(get("/api/posts/999"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.detail")
.value("Post not found with id: 999"));
}
@Test
@DisplayName("POST /api/posts returns 400 when title is blank")
void createPost_returns400WhenTitleBlank() throws Exception {
// @NotBlank on CreatePostRequest.title should reject this
// before the service is ever called
CreatePostRequest invalid = new CreatePostRequest(1L, "", "Body");
mockMvc.perform(post("/api/posts")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(invalid)))
.andExpect(status().isBadRequest());
verifyNoInteractions(postService); // service never called
}
}
Layer 3 — Integration tests with WireMock (@SpringBootTest)
This is the most valuable layer specifically for RestClient. WireMock starts a real HTTP server on a random port. The full Spring context loads, but RestClient is redirected to WireMock via @TestConfiguration.
This is the only layer that verifies the actual HTTP wire format — correct URI templates, query parameter encoding, request body structure, and response headers. The Mockito tests only prove your Java code calls the right methods. WireMock proves the HTTP calls are correctly formed.
// PostServiceIntegrationTest.java
@SpringBootTest
class PostServiceIntegrationTest {
static WireMockServer wireMockServer;
@Autowired PostService postService;
// Override RestClient to point at WireMock instead of the real API
@TestConfiguration
static class WireMockConfig {
@Bean @Primary
public RestClient testRestClient(RestClient.Builder builder) {
return builder
.baseUrl("http://localhost:" + wireMockServer.port())
.defaultStatusHandler(
s -> s.value() == 404,
(req, res) -> { throw new PostNotFoundException(-1L); }
)
.build();
}
}
@BeforeAll
static void startWireMock() {
wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());
wireMockServer.start();
WireMock.configureFor("localhost", wireMockServer.port());
}
@AfterAll static void stop() { wireMockServer.stop(); }
@AfterEach void reset() { wireMockServer.resetAll(); }
@Test
@DisplayName("getAllPosts: real HTTP GET, response deserialised correctly")
void getAllPosts_realHttp() {
// Stub WireMock to return JSON when GET /posts is called
stubFor(get(urlEqualTo("/posts"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{\"id\":1,\"userId\":1," +
"\"title\":\"First\",\"body\":\"Body\"}]")));
List<Post> posts = postService.getAllPosts();
assertThat(posts).hasSize(1);
assertThat(posts.get(0).title()).isEqualTo("First");
// Verify WireMock actually received the HTTP request
verify(getRequestedFor(urlEqualTo("/posts")));
}
@Test
@DisplayName("createPost: request body contains correct JSON fields")
void createPost_sendsCorrectBody() {
// matchingJsonPath verifies actual request body fields
// This is what the Mockito unit tests cannot catch
stubFor(post(urlEqualTo("/posts"))
.withRequestBody(matchingJsonPath("$.title", equalTo("My Post")))
.withRequestBody(matchingJsonPath("$.userId", equalTo("1")))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("{\"id\":101,\"userId\":1," +
"\"title\":\"My Post\",\"body\":\"Content\"}")));
Post created = postService.createPost(
new CreatePostRequest(1L, "My Post", "Content")
);
assertThat(created.id()).isEqualTo(101L);
verify(1, postRequestedFor(urlEqualTo("/posts")));
}
@Test
@DisplayName("getPostsByUser: userId sent as query parameter")
void getPostsByUser_sendsQueryParam() {
stubFor(get(urlPathEqualTo("/posts"))
.withQueryParam("userId", equalTo("1"))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("[{\"id\":1,\"userId\":1," +
"\"title\":\"User 1\",\"body\":\"B\"}]")));
List<Post> posts = postService.getPostsByUser(1L);
assertThat(posts).hasSize(1);
// Verify the query param was actually sent in the HTTP request
verify(getRequestedFor(urlPathEqualTo("/posts"))
.withQueryParam("userId", equalTo("1")));
}
@Test
@DisplayName("getPostById: PostNotFoundException thrown on 404")
void getPostById_throwsOnNotFound() {
stubFor(get(urlEqualTo("/posts/999"))
.willReturn(aResponse().withStatus(404)));
assertThatThrownBy(() -> postService.getPostById(999L))
.isInstanceOf(PostNotFoundException.class);
}
}
7. Ten Production Best Practices
These are lessons from shipping RestClient-based microservices in production, not from reading documentation.
Best Practice Why it matters
----------------------------------------------------------------------------
Always use @Bean Centralises base URL, timeouts, error handlers.
Enables clean test overrides.
Always set timeouts A missing timeout lets slow upstreams exhaust
your thread pool.
Handle errors at the bean Use defaultStatusHandler() - keeps service code
clean of HTTP concerns
ParameterizedTypeReference Required for List<Post> - type erasure gives
LinkedHashMap without it.
URI builder for query Never concatenate strings.
params Use .uri(b -> b.path(…).queryParam(…).build()).
No Reactive + Virtual Threads They solve the same problem. Pick one.
Mixing adds complexity for zero gain.
Three test layers JUnit (Mockito),Web layer (MockMvc),Integration
(WireMock). Each has a distinct purpose.
Java 21 records for DTOs Immutable, no boilerplate, Jackson-compatible
out of the box.
8. Virtual Threads — What Actually Changes
With spring.threads.virtual.enabled=true, every incoming HTTP request handled by Tomcat runs on a virtual thread. When your service code calls postService.getPostById(1L) and RestClient blocks waiting for the HTTP response, that virtual thread parks — it unmounts from the OS carrier thread rather than blocking it. The JVM scheduler then runs other virtual threads on the same OS thread.
You write completely normal, synchronous, blocking code. The JVM gives you reactive-level concurrency for free. No Mono, no Flux, no CompletableFuture chains.
What improves
- Tomcat can handle far more concurrent requests with the same heap
- Thread pool exhaustion under load becomes much less likely
- No thread pool tuning required — virtual threads are created on demand
Conclusion
The combination of RestClient, Java 21 virtual threads, and Spring Boot 3.2 is the most productive way to write HTTP client code in the Java ecosystem today. You get the readability of synchronous code, the scalability of reactive, and the full power of Spring’s auto-configuration — all with one property and a well-structured bean.
The three-layer test strategy — Mockito for business logic, MockMvc for the HTTP layer, WireMock for real HTTP contracts — gives you confidence at every level. Each layer catches different bugs. None of them are optional.
Quick decision guide
New Spring Boot 3.2+ project on Java 21 -> use RestClient + virtual threads
Fully reactive WebFlux application -> use WebClient
Non-Spring Java project -> use OkHttp or JDK HttpClient
Many microservice-to-microservice calls -> consider OpenFeign on top of RestClient
Existing code using RestTemplate -> keep it running, migrate incrementally to RestClient