How to Use RestTemplate in Spring Boot Application?
If you want to use RestTemplate in Spring Boot Application then first we have to create a Bean of RestTemplate class inside our configuration class file like below.
Java
@Configuration public class EmployeeConfig { // Other Beans @Bean public RestTemplate restTemplateBean() { return new RestTemplate(); } // Other Beans } |
Then we can use this in our service class with the help of @Autowired annotation something like this
Java
@Service public class EmployeeService { // Other Lines of Code @Autowired private RestTemplate restTemplate; // Other Lines of Code AddressResponse addressResponse = restTemplate.getForObject( "http://localhost:8081/address-service/address/{id}" , AddressResponse. class , id); employeeResponse.setAddressResponse(addressResponse); // ------------------ } |
Note: But it is highly recommended that we should always use the RestTemplateBuilder to create a RestTemplate instance.
So now let’s create a RestTemplate instance with the help of RestTemplateBuilder.
Spring Boot – Configure a RestTemplate with RestTemplateBuilder
RestTemplate is a synchronous REST client which performs HTTP requests using a simple template-style API. We can also state that RestTemplate class is a synchronous client and is designed to call REST services. RestTemplateBuilder is a Builder that can be used to configure and create a RestTemplate. RestTemplateBuilder provides convenient methods to register converters, error handlers, and UriTemplateHandlers. Let’s understand the concept with an example.