Saturday, 18 April 2020

Spring RestTemplateBuilder Example

Learn to use RestTemplateBuilder to create or build RestTemplate class which can be used to send HTTP requests.

1) Default RestTemplateBuilder

To inject RestTemplateBuilder, pass it as constructor argument in your service class.
MyService.java
@Service
public class MyService {
    private final RestTemplate restTemplate;
    public MyService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }
    public Details someRestCall(String name) {
        return this.restTemplate.getForObject("/{name}/details", Details.class, name);
    }
}

2) Custom RestTemplateBuilder

To create custom RestTemplateBuilder, create @Bean of type RestTemplateBuilder in Spring context.

RestTemplateBuilder Bean

RestTemplateConfig.java
@Configuration
public class RestTemplateConfig {
    @Bean
    @DependsOn(value = {"customRestTemplateBuilder"})
    public RestTemplateBuilder restTemplateBuilder()
    {
        return new RestTemplateBuilder(customRestTemplateCustomizer());
    }
    @Bean
    public CustomRestTemplateCustomizer customRestTemplateCustomizer()
    {
        return new CustomRestTemplateCustomizer();
    }
}

RestTemplateCustomizer Bean

Create custom RestTemplateCustomizer as per your requirements.
CustomRestTemplateCustomizer.java
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer
{
    @Override
    public void customize(RestTemplate restTemplate)
    {
        restTemplate.setRequestFactory( new BufferingClientHttpRequestFactory(clientHttpRequestFactory()) );
        restTemplate.setMessageConverters(Collections.singletonList(mappingJacksonHttpMessageConverter()));
        restTemplate.setInterceptors(Collections.singletonList(new RequestResponseLoggingInterceptor()));
    }
}

Inject custom RestTemplateBuilder

And inject this custom RestTemplateBuilder to your service class as given in first section i.e. similar to default RestTemplateBuilder.
MyService.java
@Service
public class MyService {
    private final RestTemplate restTemplate;
    public MyService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }
}
Drop me your questions in comments section.

No comments:

Post a Comment