W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
如果您想要一個(gè)?RestTemplate
?而不是負(fù)載均衡的,請(qǐng)創(chuàng)建一個(gè)?RestTemplate
? bean并注入它。要訪問(wèn)負(fù)載均衡的?RestTemplate
?,請(qǐng)?jiān)趧?chuàng)建?@Bean
?時(shí)使用?@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
之類的錯(cuò)誤,請(qǐng)嘗試注入RestOperations
或設(shè)置spring.aop.proxyTargetClass=true
。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: