Category: spring_boot
WebClient is a modern
Published on 24 Jun 2026
Explanation
WebClient is a modern, non-blocking HTTP
client introduced in Spring WebFlux. It
is the recommended replacement for
RestTemplate
and supports reactive programming
for better
scalability and performance.
Code:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Explanation
Create a WebClient bean to communicate
with external APIs. This bean can
be injected into services or controllers
throughout the application.
Code:
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient() {
return WebClient.builder().build();
}
}
Explanation
The get() method is used to
make HTTP GET requests. The response
body can be retrieved as a
Mono, which represents an asynchronous
single
value.
Code:
@Autowired
private WebClient webClient;
Mono<String> response = webClient.get()
.uri("https://jsonplaceholder.typicode.com/posts/1")
.retrieve()
.bodyToMono(String.class);
Explanation
WebClient responses can be mapped directly
to Java objects. This eliminates manual
JSON parsing and provides type-safe access
to API data.
Code:
public class Post {
private Long id;
private String title;
private String body;
// Getters and Setters
}
Mono<Post> post = webClient.get()
.uri("https://jsonplaceholder.typicode.com/posts/1")
.retrieve()
.bodyToMono(Post.class);
Explanation
A REST API can consume an
external service and return the response
to clients. Using WebClient, the call
remains non-blocking, improving application throughput.
Code:
@RestController
@RequestMapping("/posts")
public class PostController {
@Autowired
private WebClient webClient;
@GetMapping("/{id}")
public Mono<String> getPost(@PathVariable Long id) {
return webClient.get()
.uri("https://jsonplaceholder.typicode.com/posts/" + id)
.retrieve()
.bodyToMono(String.class);
}
}