Intro to Spring RestTemplateBuilder

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

1. Using Default RestTemplateBuilder

To inject RestTemplateBuilder, pass it as constructor argument in your service class.

@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. Using Custom RestTemplateBuilder

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

2.1. Creating RestTemplateBuilder Bean

@Configuration
public class RestTemplateConfig {

	@Bean
	@DependsOn(value = {"customRestTemplateBuilder"})
	public RestTemplateBuilder restTemplateBuilder() 
	{
	    return new RestTemplateBuilder(customRestTemplateCustomizer());
	}

	@Bean
	public CustomRestTemplateCustomizer customRestTemplateCustomizer() 
	{
	    return new CustomRestTemplateCustomizer();
	}
}

2.2. Using RestTemplateCustomizer Bean

Create custom RestTemplateCustomizer as per your requirements.

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()));
    }
}

2.3. Injecting custom RestTemplateBuilder

And inject this custom RestTemplateBuilder to your service class as given in first section i.e. similar to default RestTemplateBuilder.

@Service
public class MyService {

	private final RestTemplate restTemplate;

	public MyService(RestTemplateBuilder restTemplateBuilder) {
		this.restTemplate = restTemplateBuilder.build();
	}
}

Drop me your questions in the comments section.

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.