I have read some tutorials about implementing REST client in java web application that use SPRING to manage beans.
Every example I found, every time doing a REST request it creates new RestTemplate.
Normally web applications use singleton spring bean.
So I want to know when what is the best practice to use RestTemplate in Spring configures application ?
Use singleton RestTemplate ?
Create RestTemplate in every request. ?
Please advise and describe all situations.
One of the best ways to do this is to create a bean which would return a RestTemplate and then Autowire it in which ever class you need.
Something like this.
@Configuration
public class ProductServiceConfig {
@Value("${product.username}")
private String productServiceUsername;
@Value("${product.password}")
private String productServicePassword;
@Bean(name = "restTemplateForProductService")
public RestTemplate prepareRestTemplateForProductService() {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(productServiceUsername, productServicePassword));
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setConnectTimeout(1000);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
httpClientBuilder.setDefaultRequestConfig(requestBuilder.build());
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(rf);
}
}
This way you can set different parameters that you want for your rest call, like timeouts or credentials etc. And when you want to use, you can just do
@Autowired
RestTemplate restTemplateForProductService;
restTemplateForProductService.......
Another advantage of this over using new RestTemplate ()
is if you have to call different services through REST, then you can define multiple beans (with different configuration) which returns RestTemplates and autowire it using the name