RestTemplateBuilder bean

2020-07-27 04:47发布

问题:

My application interfaces with different rest endpoints and each one needs a specialized RestTemplate object. I am using RestTemplateBuilder to create each of the RestTemplate objects. Is it ok to clone the RestTemplateBuilder object provided by spring boot and make the changes?

@Configuration
public class Config {
@Bean
public RestTemplate googleRestTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthorization("user", "pwd123").build();
}

@Bean
public RestTemplate twitterRestTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.setConnectTimeout(5000).build();
}
}

Here, i get the singleton builder bean injected to both the bean methods. The problem i am trying to overcome is that the mutating of the same builder object. In my example, my 2nd rest template does not need basic authorization but i inadvertently get it.

回答1:

Why would you do that? Add a config class:

@Configuration
class Config {
    @Bean
    @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
    RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.build();
    }
}

inside your Controller that will consume your end-points:

@Autowired
RestTemplate restTempl;

@RequestMapping(value = "/consume", method = RequestMethod.POST)
public void samplePostMethod() {

    HttpHeaders headers = new HttpHeaders();
    HttpEntity<String> entity = new HttpEntity<String>("Data", headers);
    RequestDetails requestDetails = new RequestDetails("http://localhost:8082/endpoint1", HttpMethod.POST);
    ResponseEntity<String> response = restTempl.exchange(requestDetails.getUrl(), requestDetails.getRequestType(),
            entity, String.class);

    RequestDetails requestDetailss = new RequestDetails("http://localhost:8082/endpoint2", HttpMethod.POST);
    ResponseEntity<String> responses = restTempl.exchange(requestDetailss.getUrl(), requestDetailss.getRequestType(),
            entity, String.class);

    logger.log("{} {}", response, responses);
    return response.getBody();
}


回答2:

You can differentiate your RestTemplates using @Qualifier annotation like below.

@Configuration
public class Config {

  @Bean
  @Qualifier("googleRestTemplate")
  public RestTemplate googleRestTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthorization("user", "pwd123").build();
  }

  @Bean
  @Qualifier("twitterRestTemplate")
  public RestTemplate twitterRestTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.setConnectTimeout(5000).build();
  }
}

Then you can use any of RestTemplate beans in your controllers with these @Qualifiers.

@Autowired
@Qualifier("googleRestTemplate")
private RestTemplate restTemplate;