2021-05-04 13:01:20 -07:00

48 lines
2.8 KiB
Plaintext

[[features.resttemplate]]
== Calling REST Services with RestTemplate
If you need to call remote REST services from your application, you can use the Spring Framework's {spring-framework-api}/web/client/RestTemplate.html[`RestTemplate`] class.
Since `RestTemplate` instances often need to be customized before being used, Spring Boot does not provide any single auto-configured `RestTemplate` bean.
It does, however, auto-configure a `RestTemplateBuilder`, which can be used to create `RestTemplate` instances when needed.
The auto-configured `RestTemplateBuilder` ensures that sensible `HttpMessageConverters` are applied to `RestTemplate` instances.
The following code shows a typical example:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/features/resttemplate/MyService.java[]
----
TIP: `RestTemplateBuilder` includes a number of useful methods that can be used to quickly configure a `RestTemplate`.
For example, to add BASIC auth support, you can use `builder.basicAuthentication("user", "password").build()`.
[[features.resttemplate.customization]]
=== RestTemplate Customization
There are three main approaches to `RestTemplate` customization, depending on how broadly you want the customizations to apply.
To make the scope of any customizations as narrow as possible, inject the auto-configured `RestTemplateBuilder` and then call its methods as required.
Each method call returns a new `RestTemplateBuilder` instance, so the customizations only affect this use of the builder.
To make an application-wide, additive customization, use a `RestTemplateCustomizer` bean.
All such beans are automatically registered with the auto-configured `RestTemplateBuilder` and are applied to any templates that are built with it.
The following example shows a customizer that configures the use of a proxy for all hosts except `192.168.0.5`:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/features/resttemplate/customization/MyRestTemplateCustomizer.java[]
----
Finally, you can also create your own `RestTemplateBuilder` bean.
To prevent switching off the auto-configuration of a `RestTemplateBuilder` and prevent any `RestTemplateCustomizer` beans from being used, make sure to configure your custom instance with a `RestTemplateBuilderConfigurer`.
The following example exposes a `RestTemplateBuilder` with what Spring Boot would auto-configure, except that custom connect and read timeouts are also specified:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/features/resttemplate/customization/MyRestTemplateBuilderConfiguration.java[]
----
The most extreme (and rarely used) option is to create your own `RestTemplateBuilder` bean without using a configurer.
Doing so switches off the auto-configuration of a `RestTemplateBuilder` and prevents any `RestTemplateCustomizer` beans from being used.