1 @Configuration 2 public class MyConfiguration { 3 4 @LoadBalanced 5 @Bean 6 RestTemplate loadBalanced() { 7 return new RestTemplate(); 8 } 9 10 @Primary 11 @Bean 12 RestTemplate restTemplate() { 13 return new RestTemplate(); 14 } 15 } 16 17 public class MyClass { 18 @Autowired 19 private RestTemplate restTemplate; 20 21 @Autowired 22 @LoadBalanced 23 private RestTemplate loadBalanced; 24 25 public String doOtherStuff() { 26 return loadBalanced.getForObject("http://stores/stores", String.class); 27 } 28 29 public String doStuff() { 30 return restTemplate.getForObject("http://example.com", String.class); 31 } 32 }
如果发现报这个错误
java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89
试试注入RestOperations或者加上spring.aop.proxyTargetClass=true