@Configuration public class AuthRestTemplateConfig { @Autowired private Environment environment; @Bean(value = "authRestTemplate") public RestTemplate authRestTemplate() { RestTemplate restTemplate = new RestTemplate(); // 生产环境使用代理, 为了测试sso,咱是取消 if ("Production".equals(environment.getActiveProfiles()[0])) { SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory(); simpleClientHttpRequestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("httpproxy", 80))); restTemplate.setRequestFactory(simpleClientHttpRequestFactory); } return restTemplate; } } 我想再某个a实现中使用这个代理,想再b实现中不使用代理,我如何设置?
时间: 2024-04-11 08:27:51 浏览: 19
要在不同的实现中使用或不使用代理,可以通过在实现类中注入 `RestTemplate` 并设置不同的请求工厂来实现。
在 A 实现中使用代理,可以创建一个新的 `SimpleClientHttpRequestFactory` 并设置代理,然后将该请求工厂设置给 `RestTemplate`:
```java
public class AImpl {
private RestTemplate restTemplate;
public AImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("httpproxy", 80)));
restTemplate.setRequestFactory(requestFactory);
}
// 其他方法...
}
```
在 B 实现中不使用代理,可以直接使用注入的 `RestTemplate`,无需修改请求工厂:
```java
public class BImpl {
private RestTemplate restTemplate;
public BImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
// 其他方法...
}
```
通过这种方式,你可以在不同的实现中灵活地控制是否使用代理。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)