Spring RestTemplateBuilder Example

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

1. Default RestTemplateBuilder

To inject RestTemplateBuilder, pass it as a constructor argument in the 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. 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.setInterceptors(Collections.singletonList(new RequestResponseLoggingInterceptor()));
    }
}

You can read about the RequestResponseLoggingInterceptor in a separate post about logging the request and response with RestTemplate.

2.3. Injecting custom RestTemplateBuilder

And inject this custom RestTemplateBuilder to your service class as given in the first section i.e. similar to the 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 !!

Comments

Subscribe
Notify of
guest
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.