Dependency Injection of REST in Spring
The configurations required in the Application context file is as below:
Execute the HTTP method to the given URI template, preparing the request with the
URI Template variables are expanded using the given URI variables map.
In the referencing bean where we need to inject restTemplate we can add a property for the restTemplate as shown below:
The code for invoking REST url would be :
..
if (HttpMethod.GET == method) {
requestCallback = new AcceptHeaderRequestCallback(String.class);
} else {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity requestEntity = new HttpEntity(body, headers);
requestCallback = new HttpEntityRequestCallback(requestEntity, String.class);
}
HttpMessageConverterExtractor responseExtractor =
new HttpMessageConverterExtractor(String.class, restTemplate.getMessageConverters(), loggerCommons);
String resp = null;
try {
resp = restTemplate.execute(baseUrl + uri, method, requestCallback, responseExtractor, urlVariablesFromReq);
The java doc of this api is:
<String> String org.springframework.web.client.RestTemplate.execute(String url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<String> responseExtractor, Map<String, ?> urlVariables) throws RestClientException
Execute the HTTP method to the given URI template, preparing the request with the
RequestCallback
,
and reading the response with a ResponseExtractor
.
URI Template variables are expanded using the given URI variables map.
Specified by: execute(...)
in RestOperations
- Parameters:
- url the URL
- method the HTTP method (GET, POST, etc)
- requestCallback object that prepares the request
- responseExtractor object that extracts the return value from the response
- urlVariables the variables to expand in the template
- Returns:
- an arbitrary object, as returned by the
ResponseExtractor
- Throws:
- RestClientException
Comments
Post a Comment