Pre-Spring 5, the usual way to configure the RestTemplate for accessing single REST host was as follows:
DefaultUriTemplateHandler uriTemplateHandler = new DefaultUriTemplateHandler();
uriTemplateHandler.setBaseUrl("http://host:port");
restTemplate.setUriTemplateHandler(uriTemplateHandler);
so that when making REST calls, one can do restTemplate.getForObject("/api/foo")
instead of restTemplate.getForObject("http://host:port/api/foo")
(and possibly configure the REST root URL somewhere centralized)
In Spring 5, DefaultUriTemplateHandler
is deprecated, and the suggested replacement is DefaultUriBuilderFactory
. However, while the RestTemplate
still has the setUriTemplateHandler
method, it has no setter accepting an UriBuilderFactory
, nor an UriBuilderFactory
has anything resembling setBaseUrl
What is the proper replacement for this configuration pattern in Spring 5?
Apparently, the UriBuilderFactory
extends UriTemplateHandler
, so while the setter method in RestTemplate
stays the same, one can use an UriBuilderFactory
instance there:
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory());
As for the baseUrl setting, this has been made into fluent components with UriBuilderFactory
, so the whole setting now can take just one line:
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory("http://host:port"));
They really should document this change better, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With