[英]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.