Spring RestTemplateBuilder Example

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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Spring RestTemplateBuilder Example”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.