8
votes

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?

1

1 Answers

1
votes

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