简体   繁体   中英

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 restTemplate() {
        return new RestTemplate();
    } 

Spring boot provide default auto-configured rest template builder. 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 :

@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:

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

Also you can customize the default rest template by RestTemplateCustomizer :

public class MyRestTemplateCustomizer implements RestTemplateCustomizer {
    @Override
    public void customize(RestTemplate restTemplate) {
        restTemplate.getInterceptors().add(new MyClientHttpRequestInterceptor());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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