【问题标题】:Multiple rest templates in spring bootspring boot中的多个rest模板
【发布时间】:2019-12-02 18:03:40
【问题描述】:

我想配置多个 rest 模板客户端来访问不同的 API。两者都有不同的授权标头。我已经配置了一个,同样配置了其他的rest模板,但是会抛出错误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 具有 base64 编码授权,因此无法在此处发布该代码。

另一个 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;
    }
}

谁能告诉我如何在一个应用程序中配置多个休息模板。

【问题讨论】:

标签: spring spring-boot resttemplate


【解决方案1】:

您可以使用@VirtualTroll 提到的@Qualifier。或者为每个 api 创建一个特定的客户端 bean 并将 restemplate 实例保存在那里。

@Component
public class ApiClient1 {

    private final RestTemplate customRestTemplate;

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

    public void useApi() {
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 2016-01-27
    • 2020-10-12
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多