Reputation: 429
I am quite new in java and spring boot world so some obvious things might not be so obvious to me. I hope this question is suitable for stackoverflow...
I have a spring boot service that has some open REST API controllers and some service classes that those controllers interact with. Some service classes makes call to outside REST APis.
I use RestTemplate for making calls to outside REST apis.
My question is:
Why do I have to create a bean
//resttemplate so that we can autowire it inside services
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
// Do any additional configuration here
return builder.build();
}
and then in my service
@Autowired
private RestTemplate restTemplate = new RestTemplate();
I could also use it with Autowiring and then I wouldn't have to create a bean...
Without creating a bean @autowired fails for me.
Upvotes: 0
Views: 330
Reputation: 2755
You don't have to create the RestTemplate as bean if you don't want to. You should have a RestTemplate for each similar remote Http call that your application will make.
For example, if your application was making remote Http calls to Facebook API and you wanted to institute as specific caching policy on the responses, you would create a RestTemplate with a custom ClientHttpRequestFactory. And if your App also had to make calls to GitHub API where you wanted a different caching policy or authentication method, you might have another RestTemplate with its own ClientHttpRequestFactory.
But if your App just has standard remote Http calls with no need to customize them, you can create a single RestTemplate for your entire App and expose it as a bean (as you have done). If you don't want to do it that way and you want each service to have its own RestTemplate, just remove the bean declaration and remove the @Autowired from your service. Then that service will have its own RestTemplate.
Note: you can also use RestTemplate restTemplate = new RestTemplateBuilder().build();
for more customizations of the RestTemplate.
Upvotes: 1