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

编程知识 更新时间:2023-05-02 05:40:13

问题:

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/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;

更多推荐

springcloud 集成hystrix遇到的问题 Consider defining a bean of type 'org.springfram

本文发布于:2023-04-26 07:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/665753505a16a033041d429986656ea3.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:bean   type   defining   springcloud   hystrix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 104734文章数
  • 26228阅读数
  • 0评论数