In this post under Spring WebClient, I will explain with example the purpose and how to use “WebClient.Builder” class
In all my previous post under Spring WebClient, whenever I need to create an instance of WebClient, I used the below approach
WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");
This created an instance of “WebClient” class with default configurations and base url being “https://jsonplaceholder.typicode.com”.
If we want to use our own configuration, we cannot.
Also If I had to create another instance of “WebClient” class with same url I need to repeat the code snippet as it is again.
That is where “WebClient.Builder” class comes into picture.
It will create “WebClient” instance with user specified configuration.
And also with one instance of “WebClient.Builder” class created with user specified configuration, we can create multiple instances of “WebClient” instance without repeating the code snippet.
Below is an example of how to use it.
Main class
1 package defaultPackage;
2
3 import org.springframework.web.reactive.function.client.WebClient;
4 import reactor.core.publisher.Mono;
5
6 public class Example7 {
7 public static void main(String[] args) throws Exception {
8 WebClient.Builder webClientBuilder = WebClient.builder();
9 webClientBuilder = webClientBuilder.baseUrl("https://jsonplaceholder.typicode.com");
10 WebClient webClient = webClientBuilder.build();
11
12 Mono<String> mono = webClient.get()
13 .uri("/todos/1")
14 .retrieve()
15 .bodyToMono(String.class);
16 mono.subscribe(value -> System.out.println(value));
17 Thread.sleep(1000);
18 }
19 }
In the above code at line 8, we create an instance of “WebClient.Builder” class named “webClientBuilder”.
At line 9, we configure “webClientBuilder” instance “baseUrl” property to have “https://jsonplaceholder.typicode.com” as the base url.
At line 10, I call “build” instance method on “webClientBuilder”. This will create an instance of “WebClient” class.
As a result of which, any “WebClient” instance created from this “webClientBuilder” instance will have “https://jsonplaceholder.typicode.com” as the base url.
Then all we have to do is set the remaining part of the url in “WebClient” instance.
In this way we can use “WebClient.Builder” class to create
1) “WebClient” instance of user specified configuration
2) multiple “WebClient” instances having same configurations.