Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 864
javadev Avatar asked Jan 17 '19 13:01

javadev


People also ask

Why RestTemplate is deprecated?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof.

Can we Autowire RestTemplate in Spring boot?

The RestTemplate cannot be auto-wired without specifying the bean creation configuration. Spring boot can not find the RestTemplate as it could not be found in the loaded bean. If you autowire RestTemplate using annotations without the bean creation configuration, the error required a bean of type 'org.

Why RestTemplate is used in Spring boot?

Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object.

What is the alternative for RestTemplate in Spring boot?

reactive. client. WebClient offers a modern alternative to the RestTemplate with efficient support for both sync and async, as well as streaming scenarios. The RestTemplate will be deprecated in a future version and will not have major new features added going forward.


1 Answers

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:

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)

like image 65
Denis Zavedeev Avatar answered Nov 15 '22 06:11

Denis Zavedeev