Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate implementation vs RestOperations interface

It seems everywhere around the web there are examples of people autowiring the implementation class RestTemplate rather than it's interface RestOperations. Even in the Spring manuals and documentation the interface is said to be "not often used". Official guides like here https://spring.io/guides/gs/consuming-rest/ have the following examples:

@Bean 
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

and then injecting them in classes like

@Autowired 
public SomeClass(RestTemplate rt) {
    this.rt = rt;
}

I've always considered wiring in a concrete implementation as bad practice. Why does the use of the implementation here seem so prevalent around spring documentation and the wider web?

like image 837
Toofy Avatar asked Jul 23 '19 14:07

Toofy


People also ask

Why RestTemplate is deprecated?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof.

What is the difference between WebClient and RestTemplate?

RestTemplate uses Java Servlet API and is therefore synchronous and blocking. Conversely, WebClient is asynchronous and will not block the executing thread while waiting for the response to come back. The notification will be produced only when the response is ready. RestTemplate will still be used.

What are the advantages of the RestTemplate?

RestTemplate class is an implementation of the Template method pattern in the Spring framework. It simplifies the interaction of RESTful Web Services on the client-side. It's right time to invest in Cryptocurrencies Dogecoin !

What is alternative for RestTemplate?

WebClient offers a modern alternative to the RestTemplate with efficient support for both sync and async, as well as streaming scenarios. The RestTemplate will be deprecated in a future version and will not have major new features added going forward. We are writing a new project using spring boot 2.0.


1 Answers

I can't speak for others, they are probably have not thought about it, but RestOperations can be beneficial when thinking about testability. As the documentation says:

Not often used directly, but a useful option to enhance testability, as it can easily be mocked or stubbed.

https://docs.spring.io/spring-framework/docs/5.2.0.RELEASE/javadoc-api/org/springframework/web/client/RestOperations.html

like image 198
olahell Avatar answered Nov 05 '22 02:11

olahell