Field restTemplate in required a bean of type ‘org.springframework.web.client.RestTemplate已解决

松嘉颖
2023-12-01

背景

在Spring Cloud 示例项目中,尝试自动注入RestTemplate,报错。

解决办法

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

原因

请自行从参考中了解。

部分源码

@RestController
public class ConsumerOriginalController{

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

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

    @GetMapping("/fetch")
    public String fetchContent() {
        ServiceInstance instance = loadBalancerClient.choose("eureka-registry-producer");
        String instanceHttpAddr = "http://" + instance.getHost() + ":" + instance.getPort();
        String requestUrl = instanceHttpAddr + "/fetchProducerInfo";
        String fetchContent = restTemplate.getForObject(requestUrl, String.class);
        return fetchContent;
    }
}

参考

https://blog.csdn.net/weixin_44259720/article/details/109216423
https://stackoverflow.com/questions/28024942/how-to-autowire-resttemplate-using-annotations
https://github.com/opentracing-contrib/java-spring-web/issues/74
https://blog.csdn.net/BS0003/article/details/110000862

 类似资料: