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.

原文链接: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调用

posted @ 2022-02-25 09:20  逐星i  阅读(1518)  评论(0编辑  收藏  举报