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


https://www.cnblogs.com/EasonJim/p/7546136.html


 

錯誤如下:

復制代碼
ERROR 31473 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field restTemplate in org.springframework.cloud.zookeeper.discovery.dependency.DependencyRestTemplateAutoConfiguration required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.


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,當然,可以直接在別的地方注入紅色部分代碼即可。而且,如果哪個組件上注解了這個方法,其余都可以不用,只是一次注解即可。

解釋說明:

以上的代碼是從官方的例子代碼發現的: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;

 

參考:

https://stackoverflow.com/questions/28024942/how-to-autowire-resttemplate-using-annotations

https://gist.github.com/RealDeanZhao/38821bc1efeb7e2a9bcd554cc06cdf96


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM