How to retrieve the configured base URL from the Spring WebClient?
Asked Answered
C

2

8

The Spring reactive WebClient can be built with a base URL:

import org.springframework.web.reactive.function.client.WebClient;
...
@Bean
public WebClient webClient(WebClient.Builder builder) {
    return builder
            .baseUrl("http://example.org")
            .build();
    // or alternatively a shortcut
    // return WebClient.create("http://example.org");
}

Is there a way to retrieve the configured base URL back from an already existing WebClient instance?

Something like:

@Autowired
private WebClient webClient;
...
String baseUrl = webClient.getBaseUrl(); // I want to know how this WebClient is configured
assertEquals("http://example.org", baseUrl);

Or something like

var configuration = webClient.getConfiguration(); 
String baseUrl = configuration.getBaseUrl();
assertEquals("http://example.org", baseUrl);

I understand that the handling of the parameter is internal and implementation specific. However I don't understand why, if it is the interface who exposes the setter (via the builder or the factory method argument), it also does not expose a getter. I am not specifying the implementation when creating the instance. So I would naturally expect the interface to tell me with what value it was created. I cannot see any plausible reason why this information is not exposed in the interface itself.

Canvasback answered 21/11, 2022 at 17:12 Comment(0)
P
2

WebClient is an interface with no API to get back the base URL, so maybe some implementation class has one but that will make your code dependent on the chosen one.

Photoactinic answered 21/11, 2022 at 17:40 Comment(1)
The reason why I don't like it that it's the interface which has the setter (via the builder or the factory method argument) for the baseUrl. I am not specifying the implementation when creating the instance. So I would naturally expect the interface to tell me with what value it was created. I cannot see any plausible reason why this information is not exposed in the interface itself.Canvasback
H
0

It is possible to get this information from the implementing class, in my case DefaultWebClient is injected. So calling the code below returns the base url.

((DefaultWebClient) webClient).builder.baseUrl
Hapte answered 23/11, 2023 at 9:5 Comment(3)
Your answer, however true, goes against the philosophy of my question. As I did not specify the implementation class of the WebClient interface, my code must not be dependent on any assumptions about which class implements it.Canvasback
Unfortunately, I am not a philosopher. You should raise a change request/bug report against Spring library then.Hapte
Which spring-webflux version was it? This hack is no longer possible, as DefaultWebClient is package private (at least in spring-webflux v 6.0.11)Parmenter

© 2022 - 2024 — McMap. All rights reserved.