W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
如果您想要一個?RestTemplate
?而不是負載均衡的,請創(chuàng)建一個?RestTemplate
? bean并注入它。要訪問負載均衡的?RestTemplate
?,請在創(chuàng)建?@Bean
?時使用?@LoadBalanced
?限定符,如以下示例所示:
@Configuration
public class MyConfiguration {
@LoadBalanced
@Bean
RestTemplate loadBalanced() {
return new RestTemplate();
}
@Primary
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
public class MyClass {
@Autowired
private RestTemplate restTemplate;
@Autowired
@LoadBalanced
private RestTemplate loadBalanced;
public String doOtherStuff() {
return loadBalanced.getForObject("http://stores/stores", String.class);
}
public String doStuff() {
return restTemplate.getForObject("https://example.com", String.class);
}
}
重要
注意,在前面的示例中,在普通的
RestTemplate
聲明上使用了@Primary
批注,以消除不合格的@Autowired
注入的歧義。
如果看到諸如
java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89
之類的錯誤,請嘗試注入RestOperations
或設(shè)置spring.aop.proxyTargetClass=true
。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: