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?
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.
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.
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.
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.
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-configuredRestTemplate
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With