我在配置文件中声明了一些bean:
@Bean
public RestTemplate restTemplate()
{
return new RestTemplate(clientHttpRequestFactory());
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory()
{
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
//some config...
return factory;
}
@Bean
@Qualifier("key1")
public HttpClient httpClient()
{
//some config here too..
}
@Bean
@Qualifier("key2")
public HttpClient httpClient()
{
//some config here too..
}
然后我想两次自动连接RestTemplate:
@Autowired
@Qualifier("key1")
RestTemplate restTemplate1;
@Autowired
@Qualifier("key2")
RestTemplate restTemplate2;
HttpClinet
之前直通此链?RestTemplate
@Scope为“原型”吗?答案 0 :(得分:1)
这不起作用,因为您在配置类的HttpClient而不是RestTemplate上使用@Qualifier。
您将需要这样的内容(我写得太过头了,因此可能无法100%正常工作):
@Bean(name="key1")
public RestTemplate restTemplate1()
{
return new RestTemplate(clientHttpRequestFactory1());
}
@Bean(name="key2")
public RestTemplate restTemplate2()
{
return new RestTemplate(clientHttpRequestFactory2());
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory1()
{
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient1());
//some config...
return factory;
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory2()
{
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient2());
//some config...
return factory;
}
public HttpClient httpClient1()
{
//some config here too..
}
public HttpClient httpClient2()
{
//some config here too..
}
编辑:
可以避免代码重复,但这取决于您的特定配置以及在使用RestTemplate时是否真的需要HttpClient和ClientHttpRequestFactory作为bean。
例如:
@Bean(name = "key1")
public RestTemplate restTemplate1() {
return new RestTemplate(clientHttpRequestFactory(httpClient(/* params */)));
}
@Bean(name = "key2")
public RestTemplate restTemplate2() {
return new RestTemplate(clientHttpRequestFactory(httpClient(/* params */)));
}
public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
return factory;
}
public HttpClient httpClient(/* paramn */) {
/* create HttpClient using params */
}