简体   繁体   中英

Spring Boot Rest Template Proxy In Only Few Classes

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;

在类的构造函数中注入RestTemplate (或者更好的RestOperations )(无论如何这是最佳实践),对于需要代理配置的类,使用@Bean配置方法来实例化 bean 并传递特定的代理模板。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM