简体   繁体   English

弹簧休息模板

[英]Spring Rest Template

What is the benefit of returning new rest template in the main class?在主类中返回新的休息模板有什么好处?

From my understanding by registering a Bean restTemplate in the main class, we basically register it in advance and then every time we use the field Rest Template in other classes, Spring automatically just takes it from the container.以我的理解,在主类注册一个Bean的restTemplate,基本上是我们提前注册了,然后每次在其他类中使用Rest Template这个字段,Spring自动就直接从容器中取出来了。


    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    } 

Spring boot provide default auto-configured rest template builder. Spring boot 提供默认的自动配置的休息模板构建器。 You should use the builder to create a rest template.您应该使用构建器来创建休息模板。 From the spring documentation boc The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances :来自 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();
}

or或者

@Autowired
public MyController(RestTemplateBuilder builder) {
    this.restTemplate = = builder.build();
}

But usually you need one or more additional rest customized rest templates.但通常您需要一个或多个额外的休息自定义休息模板。 Therefore you create another one with custom configuration, for example to add some headers or ObjectMapper configuration:因此,您使用自定义配置创建另一个,例如添加一些标题或 ObjectMapper 配置:

@Bean
RestTemplate myCustormRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getInterceptors().add(new MyClientHttpRequestInterceptor());
    retun restTemplate;
}

Also you can customize the default rest template by RestTemplateCustomizer :您也可以通过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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM