不能自動裝配RestTemplate,not found
阿新 • • 發佈:2019-02-09
錯誤如下:
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 @LoadBalancedpublic 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;
參考: