My team is using RestTemplate to make external API calls. We need to configure the RestTemplate to use a proxy only in certain classes. In all other classes we want to avoid using the proxy. My first thought is to continue to @Autowire RestTemplate where the proxy is not required and do the below in all classes where it is required. I'm unhappy with this solution as it seems really clean to easily @Autowire RestTemplate but have to type the below proxy configured RestTemplate in each and every class where it is required. Are there any cleaner alternatives?
proxyrequired
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http.proxy.fmr.com", 8000)));
this.pricingRestTemplate = new RestTemplate(requestFactory);
***SOLUTION***
Created 2 beans for rest template and declared one as primary(required to avoid error)
New beans in Configuration class
@Bean
@Primary
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean(name = "proxyRestTemplate")
public RestTemplate proxyRestTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http.proxy.com", 8000));
requestFactory.setProxy(proxy);
return new RestTemplate(requestFactory);
}
and then I autowired and used the @Qualifier annotation where I needed to use the proxy
// no proxy
@Autowired
RestTemplate oauth2RestTemplate;
// yes proxy
@Autowired
@Qualifier("proxyRestTemplate")
RestTemplate proxyRestTemplate;
Inject the
RestTemplate
(or better,RestOperations
) in the class's constructors (this is best practice anyway), and for the classes where you need the proxy configuration, use an@Bean
configuration method to instantiate the bean and pass the specific proxied template.