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