Search code examples
springrestspring-bootresttemplate

Why Spring RestTemplate is not a Bean by default in Spring?


When using REST calls in Spring Boot project, and as I'm lazy guy, my hands quickly go to keyboard to write a config for a Spring's RestTemplate like this one:

  @Bean
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

This is in order not to instanciate it every time. Why don't we have it configured as a Bean by default?


Solution

  • Why don't we have it configured as a Bean by default?

    Even though it might be a little bit annoying the Spring Boot Team has a good reason to not declare a RestTemplate as a @Bean by default. It is explained in the Reference Documentation at the RestTemplate section as follows:

    Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean.

    It does, however, auto-configure a RestTemplateBuilder, which can be used to create RestTemplate instances when needed


    For the new WebClient Spring Boot creates only WebClient.Builder for the same reason (Thanks to Darren Forsythe for pointing out) - for more details see the WebClient section