使用Spring @Configuration构造RestTemplates

时间:2015-08-11 19:31:04

标签: java spring

说我有一些应用程序范围的配置:

@Configuration
public class RestTemplateConfiguration {
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public HttpClient anHttpClient() {
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        // set some properties
        // ...
        return HttpClientBuilder.create().setConnectionManager(poolingHttpClientConnectionManager).build();
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public ClientHttpRequestInterceptor aRequestInterceptor() {
        ....
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public ClientHttpRequestInterceptor anotherRequestInterceptor() {
        ....
    }
}

然后我有一些特定的服务:

@Service
public class MyService {

    private final RestTemplate myParticularRestTemplate;

    @Autowired
    public MyService(RestTemplate myParticularRestTemplate) {
         this.myParticularRestTemplate = myParticularRestTemplate;
    }

    /***
    * Some incredible application logic
    ***/

    @Configuration
    public static class Config {

        private int SOME_READ_TIMEOUT;
        private int SOME_CONNECT_TIMEOUT;

        @Bean
        public RestTemplate myParticularRestTemplate(HttpClient anHttpClient, List<ClientHttpRequestInterceptor> interceptors) {
            HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(anHttpClient);
            clientHttpRequestFactory.setReadTimeout(SOME_READ_TIMEOUT);
            clientHttpRequestFactory.setConnectTimeout(SOME_CONNECT_TIMEOUT);

            RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
            restTemplate.setInterceptors(interceptors);

            return restTemplate;
        }
    }
}

我希望将拦截器注入到RestTemplate系统范围内,但实际上,因为我必须访问RestTemplate的嵌套对象来设置特定配置,我需要我自己实例化RestTemplate - 至少我理解它。

有没有更好的解决方法,不需要配置特定RestTemplate来了解List<ClientHttpRequestInterceptor>

0 个答案:

没有答案