Configure a RestTemplate with RestTemplateBuilder

1. Introduction

In this quick tutorial, we’re going to look at how to configure a Spring RestTemplate bean.

Let’s start by discussing the three main configuration types:

  • using the default RestTemplateBuilder
  • using a RestTemplateCustomizer
  • creating our own RestTemplateBuilder

To be able to test this easily, please follow the guide on how to set up a simple Spring Boot application.

2. Configuration Using the Default RestTemplateBuilder

To configure a RestTemplate this way, we need to inject the default RestTemplateBuilder bean provided by Spring Boot into our classes:

private RestTemplate restTemplate;

@Autowired
public HelloController(RestTemplateBuilder builder) {
    this.restTemplate = builder.build();
}

The RestTemplate bean created with this method has its scope limited to the class in which we build it.

3. Configuration Using a RestTemplateCustomizer

With this approach, we can create an application-wide, additive customization.

This is a slightly more complicated approach. For this we need to create a class that implements RestTemplateCustomizer, and define it as a bean:

public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
    @Override
    public void customize(RestTemplate restTemplate) {
        restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor());
    }
}

The CustomClientHttpRequestInterceptor interceptor is doing basic logging of the request:

public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    private static Logger LOGGER = LoggerFactory
      .getLogger(CustomClientHttpRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(
      HttpRequest request, byte[] body, 
      ClientHttpRequestExecution execution) throws IOException {
 
        logRequestDetails(request);
        return execution.execute(request, body);
    }
    private void logRequestDetails(HttpRequest request) {
        LOGGER.info("Headers: {}", request.getHeaders());
        LOGGER.info("Request Method: {}", request.getMethod());
        LOGGER.info("Request URI: {}", request.getURI());
    }
}

Now, we define CustomRestTemplateCustomizer as a bean in a configuration class or in our Spring Boot application class:

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

With this configuration, every RestTemplate that we’ll use in our application will have the custom interceptor set on it.

4. Configuration by Creating Our Own RestTemplateBuilder

This is the most extreme approach to customizing a RestTemplate. It disables the default auto-configuration of RestTemplateBuilder, so we need to define it ourselves:

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

After this, we can inject the custom builder into our classes like we’d do with a default RestTemplateBuilder and create a RestTemplate as usual:

private RestTemplate restTemplate;

@Autowired
public HelloController(RestTemplateBuilder builder) {
    this.restTemplate = builder.build();
}

5. Conclusion

We’ve seen how to configure a RestTemplate with the default RestTemplateBuilder, building our own RestTemplateBuilder, or using a RestTemplateCustomizer bean.

As always, the full codebase for this example can be found in our GitHub repository.

Related posts:

Java Program to Find Path Between Two Nodes in a Graph
Java Program to Perform Searching in a 2-Dimension K-D Tree
Java – Create a File
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Java Program to Implement Sorted Circular Doubly Linked List
Java Program to Implement Radix Sort
Convert Hex to ASCII in Java
Removing all Nulls from a List in Java
Java Program to Implement Splay Tree
Java Program to Convert a Decimal Number to Binary Number using Stacks
REST Pagination in Spring
How to Find an Element in a List with Java
Java Optional as Return Type
Java InputStream to String
Comparing Strings in Java
Serialize Only Fields that meet a Custom Criteria with Jackson
Guide to PriorityBlockingQueue in Java
Spring Boot with Multiple SQL Import Files
Converting Between Byte Arrays and Hexadecimal Strings in Java
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Java Program to Implement Selection Sort
Introduction to Project Reactor Bus
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Generating Random Numbers in a Range in Java
Reactive WebSockets with Spring 5
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Hướng dẫn Java Design Pattern – State
Wiring in Spring: @Autowired, @Resource and @Inject
ArrayList trong java
Spring Autowiring of Generic Types