3

What's the proper way of creating RestTemplate instance in Spring?

Let's say I have a service where I do multi-thread requests via rest template.

I found various variants in different tutorials:

1) create it when it is needed:

RestTemplate restTemplate = new RestTemplate();

2) declare it as bean:

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

(or what is the same way - in XML configuration file).

and then autowire it... Will it be always thread-safe in this case?

Is any performance difference? What is more "spring" style?

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • Ok, will it be always thread-safe? – Andremoniy Feb 08 '17 at 17:02
  • If you create it as needed then you need to configure it every time. It's supposed to be a singleton bean, and yes it's thread-safe. – OrangeDog Feb 08 '17 at 17:06
  • 1
    There are also questions like http://stackoverflow.com/questions/21242812/how-to-use-resttemplate-efficiently-in-multithreaded-environment – Sotirios Delimanolis Feb 08 '17 at 17:21
  • 2
    I voted to reopen because the given link answers only to the one question (which is not the main one here, I suppose) – Andrew Tobilko Feb 08 '17 at 17:25
  • @SotiriosDelimanolis my question is more about proper way of declaring RestTemplate, thread-safety is just one of subquestions. I bolded initially main questions – Andremoniy Feb 08 '17 at 18:00
  • And linked question has nothing to do with spring, btw – Andremoniy Feb 08 '17 at 18:01
  • 1
    There is no such thing as _spring style_. Whether you declare a bean or initialize an object yourself is unrelated to `RestTemplate`. That's a choice you need to make. Performance is implied by thread safety. If the object is thread safe, then it makes no sense to keep initializing new instances. It only makes sense if you need custom configurations for each, but we can't answer that because it's not part of your question. – Sotirios Delimanolis Feb 08 '17 at 18:25
  • This should be an answer, like: do it in this way or in both ways. I still do not agree that it is duplicate – Andremoniy Feb 08 '17 at 18:37

1 Answers1

2

Where to create RestTemplate in Spring?

It may be defined in any configuration class which is responsible for web client settings if there is any. It is OK to declare it as a @Bean with the singleton scope (one instance per the container) by assuming that's quite a heavy object.

If you were in a Spring Boot application, I would suggest using a RestTemplateBuilder which could help construct a RestTemplate more conveniently.

What is more "spring" style?

"Spring style" is not to resolve dependencies manually and write lines like

RestTemplate restTemplate = new RestTemplate();

Leave this matter to the framework.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142