Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the replacement for deprecated DefaultUriTemplateHandler for RestTemplate?

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?

like image 875
Alex Savitsky Avatar asked Mar 07 '23 17:03

Alex Savitsky


1 Answers

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.

like image 77
Alex Savitsky Avatar answered Mar 14 '23 10:03

Alex Savitsky