I have following class in my code, you can say it is just a wrapper over standard RestTemplate
. So whenever we have to make an external request instead of using RestTemplate
we autowire
custom MyRestTemplate
.
@Service
@Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyRestTemplateImpl implements MyRestTemplate {
private final RestTemplate restTemplate;
private Logger logger = LogManager.getLogger(MyRestTemplateImpl.class);
@Autowired
public MyRestTemplateImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException {
ResponseEntity responseEntity = restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
return responseEntity;
}
}
Now the issue is I am making some Async
rest calls, which in turn calls MyRestTemplate
to make external REST requests.
But it fails giving following error:
Error creating bean with name 'scopedTarget.myRestTemplateImpl': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton
I understand that it is because a new thread is spawned for Async
operation and scope request
is invalid for that child thread. And it can be solved by using very nice solutions from How to enable request scope in async task executor but, I don't want to go for it at this moment as this Async operation is not so common and also I have some time constraints.
So, My main question is, if I make MyRestTemplateImpl
as singleton
everything works fine, I did not come across any such issue.
But there are many methods using MyRestTemplateImpl
for external requests and traffic on the application is also heavy.
Will changing it to Singleton
from Request
cause any adverse effects like slowness, race condition or any such harmful effect that I am unaware of or not come across as of now ?
If yes, if you can please give proper explanation apart from basic difference between scopes for it would be great as it will give me better reasoning while scoping the beans while I code now onwards. If no, why ?
I know for each request a new bean will be created but please explain what are the actual use cases for request
scope with small examples ?