赶知识网

org.springframework.web.client.RestTemplate‘ that could not be found

2022-04-06 / 995次点击 Js/Css/jQuery

问题描述:

初学 SpringCloud 架构,配置ribbon消费者服务,启动该服务时候报出标题中的错误,导致程序启动失败。


完整的错误信息如下:


Field restTemplate in com.cloud.ribbon_consumer.project.service.HelloService required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.


其中,“com.cloud.ribbon_consumer.project.service.HelloService”是我的示例中使用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 相关配置,代码如下:

@Bean

    RestTemplate restTemplate() {

        return new RestTemplate();

    }

有用 没用 1

Top10

沪ICP备09053415号 © 赶知识网