简体   繁体   English

Spring Boot Rest 模板代理只有几个类

[英]Spring Boot Rest Template Proxy In Only Few Classes

My team is using RestTemplate to make external API calls.我的团队正在使用 RestTemplate 进行外部 API 调用。 We need to configure the RestTemplate to use a proxy only in certain classes.我们需要将 RestTemplate 配置为仅在某些类中使用代理。 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.我的第一个想法是继续使用不需要代理的@Autowire RestTemplate,并在所有需要的类中执行以下操作。 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.我对这个解决方案不满意,因为它看起来很容易@Autowire RestTemplate 很干净,但必须在每个需要它的类中键入以下代理配置的 RestTemplate。 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) 为 rest 模板创建了 2 个 bean 并将其中一个声明为主要(需要避免错误)

New beans in Configuration class配置类中的新 bean

 @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然后我自动装配并在需要使用代理的地方使用了@Qualifier 注释

 // no proxy @Autowired RestTemplate oauth2RestTemplate; // yes proxy @Autowired @Qualifier("proxyRestTemplate") RestTemplate proxyRestTemplate;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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