似乎网络上到处都有人们 Autowiring 实现类 RestTemplate 而不是它的接口(interface) RestOperations 的例子。即使在 Spring 手册和文档中,该接口(interface)也被称为“不经常使用”。像这里这样的官方指南https://spring.io/guides/gs/consuming-rest/有以下例子:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
然后将它们注入(inject)到类中@Autowired
public SomeClass(RestTemplate rt) {
this.rt = rt;
}
我一直认为在具体实现中布线是不好的做法。为什么这里的实现在 Spring 文档和更广泛的网络中如此普遍?
最佳答案
我不能为别人说话,他们可能没有想过,但是RestOperations
在考虑可测试性时可能是有益的。正如文档所说:
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
关于java - Spring RestTemplate 实现与 RestOperations 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57165954/