Spring RestTemplate 实现与 RestOperations 接口

Too*_*ofy 8 java spring resttemplate

似乎网络上到处都有人们自动装配实现类 RestTemplate 而不是它的接口 RestOperations 的例子。即使在 Spring 手册和文档中,接口也被称为“不经常使用”。像这里https://spring.io/guides/gs/sumption-rest/这样的官方指南有以下示例:

@Bean 
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}
Run Code Online (Sandbox Code Playgroud)

然后将它们注入到类中

@Autowired 
public SomeClass(RestTemplate rt) {
    this.rt = rt;
}
Run Code Online (Sandbox Code Playgroud)

我一直认为在具体实现中接线是不好的做法。为什么这里的实现在 spring 文档和更广泛的网络中如此普遍?

ola*_*ell 2

我不能代表其他人,他们可能没有考虑过这一点,但RestOperations在考虑可测试性时可能是有益的。正如文档所说:

通常不直接使用,但它是增强可测试性的有用选项,因为它可以轻松地被模拟或存根。

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