spring boot中的多个rest模板
我想配置多个rest模板客户端以访问不同的API。两者都有不同的授权头。我已经配置了一个rest模板,和配置其他rest模板的方式相同,但这会引发错误spring boot中的多个rest模板,spring,spring-boot,resttemplate,Spring,Spring Boot,Resttemplate,我想配置多个rest模板客户端以访问不同的API。两者都有不同的授权头。我已经配置了一个rest模板,和配置其他rest模板的方式相同,但这会引发错误bean“restTemplate”在类路径资源中定义。类无法注册。 @Configuration public class RestTemplateConfig { @Autowired private HeaderRequestInterceptor headerRequestInterceptor; //cons
bean“restTemplate”在类路径资源中定义。类无法注册。
@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编码的授权,因此无法在此处发布该代码
另一个REST模板:
@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;
}
}
有人能告诉我如何在一个应用程序中配置多个rest模板吗。您可以使用@VirtualTroll提到的
@Qualifier
。或者根据api创建一个特定的客户端bean,并将重新模板实例保存在那里
@Component
public class ApiClient1 {
private final RestTemplate customRestTemplate;
public ApiClient1() {
this.customRestTemplate = ...
}
public void useApi() {
}
}
你可以用一个限定词是的,明白了。使用@Bean(name=”“)注释了2个rest模板,并使用@Qualifier自动连接它们。