原文鏈接:https://blog.csdn.net/weixin_44259720/article/details/109216423
問題描述:
搭建SpringCloud 架構,配置者服務,啟動該服務時候報出標題中的錯誤,導致程序啟動失敗。
完整的錯誤信息如下:
Field restTemplate in com.cloud.ribbon_consumer.project.service.xxxService required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
其中,“com.cloud.ribbon_consumer.project.service.xxxService”是我的示例中使用RestTemplate實例的路徑。
spring cloud 架構開發中,有兩種消費的方式:RestTemplate+ribbon,feign。
兩者最大的區別就是區別就是:
feign 消費是通過注解的方式進行的消費模式,它默認打開了負載均衡;
而 ribbon 消費需要手動配置負載均衡;
其中,使用“RestTemplate + ribbon”方式配置消費時,當我們將 RestTemplate 通過 @Autowired 注解注入到一個類中,啟動服務就可能會報該(標題中的)錯誤。
【原因在於】:
在 Spring Boot 1.3版本中,會默認提供一個RestTemplate的實例Bean,而在 Spring Boot 1.4以及以后的版本中,這個默認的bean不再提供了,我們需要在Application啟動時,手動創建一個RestTemplate的配置。
這樣,我們在類中通過注解 @Autowired 使用 TestTemplate 的時候,程序就可以找到被實例化的 TestTemplate,就不會出現上述的報錯了。
解決方案:
在 Spring Boot 項目啟動類 xxxApplication 中,設置手動引入 RestTemplate 相關配置,代碼如下:
@SpringBootApplication(scanBasePackages = "com.xxx")
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
ps:原第三方RestTemplate調用換成httpclient調用