springcloud 集成hystrix遇到的问题 Consider defining a bean of type 'org.springframework.web.client.RestTemp

问题:

Description:

Field restTemplate in wenqiao.consumer_ribbon_with_hystrix.controller.controller required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

解决方法:

在网上搜了一下

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class Config {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

说明:可以封装一个Cinfig类,最主要是红色部分的RestTemplate,当然,可以直接在别的地方注入红色部分代码即可。而且,如果哪个组件上注解了这个方法,其余都可以不用,只是一次注解即可。

 

说明:可以封装一个Cinfig类,最主要是红色部分的RestTemplate,当然,可以直接在别的地方注入红色部分代码即可。而且,如果哪个组件上注解了这个方法,其余都可以不用,只是一次注解即可。

解释说明:

以上的代码是从官方的例子代码发现的:https://github.com/spring-cloud/spring-cloud-zookeeper/blob/master/spring-cloud-zookeeper-sample/src/main/java/org/springframework/cloud/zookeeper/sample/SampleZookeeperApplication.java

如果RestTemplate没有定义,您将看到错误

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

或者

No qualifying bean of type [org.springframework.web.client.RestTemplate] found

如何通过注解定义RestTemplate

这取决于你使用的是什么版本的技术会影响你如何定义你的“配置类RestTemplate。

Spring >=4且没有Spring Boot

简单地定义一个@Bean

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Spring Boot<=1.3

无需定义,Spring Boot自动为您定义了一个。

Spring Boot >= 1.4

Spring Boot不再自动定义一个RestTemplate,而是定义了一个RestTemplateBuilder允许您更好地控制所RestTemplate创建的对象。你可以RestTemplateBuilder在你的@Bean方法中注入一个参数来创建一个RestTemplate

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here
   return builder.build();
}

在你的类上使用它

@Autowired
private RestTemplate restTemplate;

或者

@Inject
private RestTemplate restTemplate;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值