2

I want to configure multiple rest template clients to access different API's. Both are having different authorization headers. I already configured one, Same way configured other rest template too, but that throws error bean 'restTemplate' defined in class path resource .class could not be registered..

@Configuration
public class RestTemplateConfig {


    @Autowired
    private HeaderRequestInterceptor headerRequestInterceptor;

    //constructor
    public RestClientConfig() {}

    @Bean
    public RestTemplate restTemplate( RestTemplateBuilder builder ) {
        RestTemplate restTemplate = builder.build();
        restTemplate.setInterceptors(Collections.singletonList(headerRequestInterceptor));
        return restTemplate;
    }

}

HeaderRequestInterceptor has base64 encoded authorization, so could not post that code here.

Another RestTemplate:

@Configuration
public class AnotherRestClientConfig {


    @Autowired
    private AnotherHeaderRequestInterceptor anotherHeaderRequestInterceptor;

    @Bean
    public RestTemplate restTemplate( RestTemplateBuilder builder ) {
        RestTemplate restTemplate = builder.build();
        restTemplate.setInterceptors(Collections.singletonList(anotherHeaderRequestInterceptor));
        return restTemplate;
    }
}

Could someone let me know how to configure multiple rest templates in an application.

Vipul
  • 545
  • 1
  • 8
  • 30
  • 3
    You could use a qualifier https://stackoverflow.com/questions/4447877/how-does-spring-autowire-by-name-when-more-than-one-matching-bean-is-found – VirtualTroll Dec 02 '19 at 18:05
  • 1
    yeah, got it. annotated 2 rest templates with named @Bean(name="") & autowired them using @Qualifier. – Vipul Dec 02 '19 at 18:14

1 Answers1

2

you could use @Qualifier as mentioned by @VirtualTroll. Or create a specific client bean per api and hold the restemplate instance there.

@Component
public class ApiClient1 {

    private final RestTemplate customRestTemplate;

    public ApiClient1() {
        this.customRestTemplate = ...
    }

    public void useApi() {
    }
}
Marc Stroebel
  • 2,295
  • 1
  • 12
  • 21