在主类中返回新的rest模板有什么好处?
据我了解,通过在主类中注册Bean restTemplate,我们基本上是预先注册的,然后每次在其他类中使用Rest模板字段时,Spring都会自动从容器中获取它。
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
答案 0 :(得分:6)
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());
}
}