[英]Spring Rest Template
在主類中返回新的休息模板有什么好處?
以我的理解,在主類注冊一個Bean的restTemplate,基本上是我們提前注冊了,然后每次在其他類中使用Rest Template這個字段,Spring自動就直接從容器中取出來了。
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
Spring boot 提供默認的自動配置的休息模板構建器。 您應該使用構建器來創建休息模板。 來自 spring 文檔 boc The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances
:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.setReadTimeout(httpClientReadTimeout).build();
}
或者
@Autowired
public MyController(RestTemplateBuilder builder) {
this.restTemplate = = builder.build();
}
但通常您需要一個或多個額外的休息自定義休息模板。 因此,您使用自定義配置創建另一個,例如添加一些標題或 ObjectMapper 配置:
@Bean
RestTemplate myCustormRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(new MyClientHttpRequestInterceptor());
retun restTemplate;
}
您也可以通過RestTemplateCustomizer自定義默認休息模板:
public class MyRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.getInterceptors().add(new MyClientHttpRequestInterceptor());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.