RestTemplate Getforobject
By AmarSivas | | Updated : 2021-10-15 | Viewed : 177 times

We learned about
Table of Contents:
Resttemplate Getforobject
T getForObject(String url, Class<T> responseType, Map<String,?> uriVariables)
T getForObject(String url, Class<T> responseType, Object... uriVariables)
T getForObject(URI url, Class<T> responseType)
Now we will see the nice examples for the above methods.
Resttemplate Getforobject Example
We will explore the different types of methods of getForObject(). See the below-given sections.
RestTemplate Getforobject With Parameters
//Using GetForObject with Parameters
public CustomerDetails getCustDetailsGetForObject(Long id) {
Map<String, Object> requestMap = new HashMap();
requestMap.put("id", id);
return restTemplate.getForObject("http://localhost:8082/restTemplateServer/api/customerDetails/{id}", CustomerDetails.class, requestMap);
}
@GetMapping("/customerDetails/{id}")
public ResponseEntity<?> getCustomerDetails(@PathVariable Long id) {
CustomerDetails customerDetails = customerDetailsServiceImpl.getCustomerDetails(id);
return ResponseEntity.ok(customerDetails);
}
So here we used getForObject() with URI variables. So these variables are used as path variables in other microservices. Here you can see the id used as URI variable in the getForObject() methods.
RestTemplate Getforobject
Notice below given example for getForObject(). Here it does not have URI variables.
//Using GetForObject
public List<CustomerDetails> getCustDetailsUsingGetForObject() {
return restTemplate.getForObject("http://localhost:8082/restTemplateServer/api/customerDetails", List.class);
}
@GetMapping("/customerDetails")
public ResponseEntity<?> getCustomerDetails() {
List<CustomerDetails> CustomerDetailList = customerDetailsServiceImpl.getCustomerDetails();
return ResponseEntity.ok(CustomerDetailList);
}
So when client microservice request for the object using
GitRepo is here SpringBoot-RestTemplate-Example-App for exploring the entire code base.