Integration: Resttemplate
Integration: Resttemplate
Integration
Version 5.3.22
Back to index
1. REST Endpoints
1.1. RestTemplate
1.1.1. Initialization
URIs
Headers
1.1.2. Body
1.1.3. Message Conversion
1.1.4. Jackson JSON Views
Multipart
1.2. Using AsyncRestTemplate (Deprecated)
2. Remoting and Web Services
2.1. AMQP
2.2. Considerations when Choosing a Technology
2.3. Java Web Services
2.3.1. Exposing Servlet-based Web Services by Using JAX-WS
2.3.2. Exporting Standalone Web Services by Using JAX-WS
2.3.3. Exporting Web Services by Using JAX-WS RI’s Spring Support
2.3.4. Accessing Web Services by Using JAX-WS
2.4. RMI (Deprecated)
2.4.1. Exporting the Service by Using RmiServiceExporter
2.4.2. Linking in the Service at the Client
2.5. Using Hessian to Remotely Call Services through HTTP (Deprecated)
2.5.1. Hessian
2.5.2. Exposing Your Beans by Using HessianServiceExporter
2.5.3. Linking in the Service on the Client
2.5.4. Applying HTTP Basic Authentication to a Service Exposed through Hessian
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 1/15
7/31/22, 5:51 PM Integration
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 2/15
7/31/22, 5:51 PM Integration
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 3/15
7/31/22, 5:51 PM Integration
6.1. Usage
6.1.1. Basic MailSender and SimpleMailMessage Usage
6.1.2. Using JavaMailSender and MimeMessagePreparator
6.2. Using the JavaMail MimeMessageHelper
6.2.1. Sending Attachments and Inline Resources
Attachments
Inline Resources
6.2.2. Creating Email Content by Using a Templating Library
7. Task Execution and Scheduling
7.1. The Spring TaskExecutor Abstraction
7.1.1. TaskExecutor Types
7.1.2. Using a TaskExecutor
7.2. The Spring TaskScheduler Abstraction
7.2.1. Trigger Interface
7.2.2. Trigger Implementations
7.2.3. TaskScheduler implementations
7.3. Annotation Support for Scheduling and Asynchronous Execution
7.3.1. Enable Scheduling Annotations
7.3.2. The @Scheduled annotation
7.3.3. The @Async annotation
7.3.4. Executor Qualification with @Async
7.3.5. Exception Management with @Async
7.4. The task Namespace
7.4.1. The 'scheduler' Element
7.4.2. The executor Element
7.4.3. The 'scheduled-tasks' Element
7.5. Cron Expressions
7.5.1. Macros
7.6. Using the Quartz Scheduler
7.6.1. Using the JobDetailFactoryBean
7.6.2. Using the MethodInvokingJobDetailFactoryBean
7.6.3. Wiring up Jobs by Using Triggers and SchedulerFactoryBean
8. Cache Abstraction
8.1. Understanding the Cache Abstraction
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 4/15
7/31/22, 5:51 PM Integration
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 5/15
7/31/22, 5:51 PM Integration
<jee:jndi-lookup/> (Complex)
<jee:local-slsb/> (Simple)
<jee:local-slsb/> (Complex)
<jee:remote-slsb/>
9.1.2. The jms Schema
9.1.3. Using <context:mbean-export/>
9.1.4. The cache Schema
This part of the reference documentation covers Spring Framework’s integration with a number
of technologies.
1. REST Endpoints
The Spring Framework provides two choices for making calls to REST endpoints:
RestTemplate : The original Spring REST client with a synchronous, template method API.
As of 5.0 the RestTemplate is in maintenance mode, with only minor requests for changes
and bugs to be accepted going forward. Please, consider using the WebClient which offers
a more modern API and supports sync, async, and streaming scenarios.
1.1. RestTemplate
The RestTemplate provides a higher level API over HTTP client libraries. It makes it easy to
invoke REST endpoints in a single line. It exposes the following groups of overloaded methods:
Method Description
group
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 6/15
7/31/22, 5:51 PM Integration
Method Description
group
getFor Retrieves a ResponseEntity (that is, status, headers, and body) by using GET.
Entity
postFo Creates a new resource by using POST and returns the Location header from the
rLocat
response.
ion
postFo Creates a new resource by using POST and returns the representation from the
rObjec
response.
t
postFo Creates a new resource by using POST and returns the representation from the
rEntit
response.
y
patchF Updates a resource by using PATCH and returns the representation from the
orObje
response. Note that the JDK HttpURLConnection does not support PATCH , but
ct
Apache HttpComponents and others do.
exchan More generalized (and less opinionated) version of the preceding methods that
ge
provides extra flexibility when needed. It accepts a RequestEntity (including
HTTP method, URL, headers, and body as input) and returns a ResponseEntity .
These methods allow the use of ParameterizedTypeReference instead of Class to
specify a response type with generics.
execut The most generalized way to perform a request, with full control over request
e
preparation and response extraction through callback interfaces.
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 7/15
7/31/22, 5:51 PM Integration
1.1.1. Initialization
The default constructor uses java.net.HttpURLConnection to perform requests. You can switch to
a different HTTP library with an implementation of ClientHttpRequestFactory . There is built-in
support for the following:
Apache HttpComponents
Netty
OkHttp
For example, to switch to Apache HttpComponents, you can use the following:
Note that the java.net implementation for HTTP requests can raise an exception when
accessing the status of a response that represents an error (such as 401). If this is an
issue, switch to another HTTP client library.
URIs
Many of the RestTemplate methods accept a URI template and URI template variables, either as
a String variable argument, or as Map<String,String> .
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 8/15
7/31/22, 5:51 PM Integration
Keep in mind URI templates are automatically encoded, as the following example shows:
You can use the uriTemplateHandler property of RestTemplate to customize how URIs are
encoded. Alternatively, you can prepare a java.net.URI and pass it into one of
the RestTemplate methods that accepts a URI .
For more details on working with and encoding URIs, see URI Links.
Headers
You can use the exchange() methods to specify request headers, as the following example
shows:
.header("MyRequestHeader", "MyValue")
.build();
You can obtain response headers through many RestTemplate method variants that
return ResponseEntity .
1.1.2. Body
Objects passed into and returned from RestTemplate methods are converted to and from raw
content with the help of an HttpMessageConverter .
On a POST, an input object is serialized to the request body, as the following example shows:
You need not explicitly set the Content-Type header of the request. In most cases, you can find a
compatible message converter based on the source Object type, and the chosen message
converter sets the content type accordingly. If necessary, you can use the exchange methods to
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 9/15
7/31/22, 5:51 PM Integration
explicitly provide the Content-Type request header, and that, in turn, influences what message
converter is selected.
On a GET, the body of the response is deserialized to an output Object , as the following
example shows:
The Accept header of the request does not need to be explicitly set. In most cases, a
compatible message converter can be found based on the expected response type, which then
helps to populate the Accept header. If necessary, you can use the exchange methods to
provide the Accept header explicitly.
The spring-web module contains the HttpMessageConverter contract for reading and writing the
body of HTTP requests and responses
through InputStream and OutputStream . HttpMessageConverter instances are used on the client
side (for example, in the RestTemplate ) and on the server side (for example, in Spring MVC
REST controllers).
Concrete implementations for the main media (MIME) types are provided in the framework and
are, by default, registered with the RestTemplate on the client side and
with RequestMappingHandlerAdapter on the server side (see Configuring Message Converters).
The implementations of HttpMessageConverter are described in the following sections. For all
converters, a default media type is used, but you can override it by setting
the supportedMediaTypes bean property. The following table describes each implementation:
MessageConverter Description
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 10/15
7/31/22, 5:51 PM Integration
MessageConverter Description
ByteArrayHttpMessa An HttpMessageConverter implementation that can read and write byte
geConverter
arrays from the HTTP request and response. By default, this converter
supports all media types ( */* ) and writes with a Content-
Type of application/octet-stream . You can override this by setting
the supportedMediaTypes property and
overriding getContentType(byte[]) .
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 11/15
7/31/22, 5:51 PM Integration
MessageConverter Description
value.setSerializationView(User.WithoutPasswordView.class);
RequestEntity<MappingJacksonValue> requestEntity =
RequestEntity.post(new URI("https://example.com/user")).body(value);
Multipart
To send multipart data, you need to provide a MultiValueMap<String, Object> whose values
may be an Object for part content, a Resource for a file part, or an HttpEntity for part content
with headers. For example:
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 12/15
7/31/22, 5:51 PM Integration
parts.add("fieldPart", "fieldValue");
headers.setContentType(MediaType.APPLICATION_XML);
In most cases, you do not have to specify the Content-Type for each part. The content type is
determined automatically based on the HttpMessageConverter chosen to serialize it or, in the
case of a Resource based on the file extension. If necessary, you can explicitly provide
the MediaType with an HttpEntity wrapper.
Once the MultiValueMap is ready, you can pass it to the RestTemplate , as show below:
If the MultiValueMap contains at least one non- String value, the Content-Type is set
to multipart/form-data by the FormHttpMessageConverter . If
the MultiValueMap has String values the Content-Type is defaulted to application/x-www-
form-urlencoded . If necessary the Content-Type may also be set explicitly.
Java Web Services: Spring provides remoting support for web services through JAX-WS.
AMQP: Remoting via AMQP as the underlying protocol is supported by the separate Spring
AMQP project.
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 13/15
7/31/22, 5:51 PM Integration
As of Spring Framework 5.3, support for several remoting technologies is now deprecated
for security reasons and broader industry support. Supporting infrastructure will be
removed from Spring Framework for its next major release.
The following remoting technologies are now deprecated and will not be replaced:
Spring HTTP Invoker (Deprecated): Spring provides a special remoting strategy that allows
for Java serialization though HTTP, supporting any Java interface (as the RMI invoker does).
The corresponding support classes
are HttpInvokerProxyFactoryBean and HttpInvokerServiceExporter .
JMS (Deprecated): Remoting via JMS as the underlying protocol is supported through
the JmsInvokerServiceExporter and JmsInvokerProxyFactoryBean classes in the spring-
jms module.
While discussing the remoting capabilities of Spring, we use the following domain model and
corresponding services:
return name;
this.name = name;
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 14/15
7/31/22, 5:51 PM Integration
// do something...
// do something...
This section starts by exposing the service to a remote client by using RMI and talk a bit about
the drawbacks of using RMI. It then continues with an example that uses Hessian as the
protocol.
2.1. AMQP
Remoting via AMQP as the underlying protocol is supported in the Spring AMQP project. For
further details please visit the Spring Remoting section of the Spring AMQP reference.
The main reason why auto-detection of implemented interfaces does not occur for remote
interfaces is to avoid opening too many doors to remote callers. The target object might
implement internal callback interfaces, such
as InitializingBean or DisposableBean which one would not want to expose to callers.
Offering a proxy with all interfaces implemented by the target usually does not matter in the
local case. However, when you export a remote service, you should expose a specific
service interface, with specific operations intended for remote usage. Besides internal
callback interfaces, the target might implement multiple business interfaces, with only one
of them intended for remote exposure. For these reasons, we require such a service
interface to be specified.
This is a trade-off between configuration convenience and the risk of accidental exposure
of internal methods. Always specifying a service interface is not too much effort and puts
you on the safe side regarding cont
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#spring-integration 15/15