2

Is it better to keep RestTemplate in memory than creating new RestTemplate with every request ?

Example: With every request in my api, my api request to another api with REST. So my method can look like this :

exampleMethod() {
   RestTemplate restTemplate = new RestTemplate;
   restTemplate.getForObject(...);
}

or :

private RestTemplate restTemplate;

exampleMethod() {
   if(restTemplate == null) {
      restTemplate = new RestTemplate;
   }
   restTemplate.getForObject(...)
}
Kenez92
  • 136
  • 2
  • 8

1 Answers1

3

RestTemplate is designed to be thread-safe and reusable.

RestTemplate is just a facade that doesn't perform actual network operations. It delegates network operations to a HTTP client implementation. This HTTP client implementation can be expensive to create and often handles network level optimizations e.g. caching of connections per origin. You usually want to reuse this HTTP client implementation and this can be achieved by reusing RestTemplate.

Normally you would create RestTemplate as a singleton bean within Spring context. Especially in Spring Boot this is important and you shouldn't use new RestTemplate() syntax because it will not inject all registered customizers.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • 1
    additionally, if you use AutoConfigurations in Spring Boot, the container will create a RestTemplate automatically for you, and you can simply inject (autowire) it. – Tom Elias Jun 02 '21 at 09:17