RestTemplate加@Autowired注入不了
1、在啟動類加入
如圖箭頭所示代碼:
然后在進行@Autowired發現不報錯了。
完美解決
SpringBoot 如何注入RestTemplate
創建一個文件夾 ,我這邊習慣于創建config文件夾
將下面的一段代碼放到里面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.RestTemplate; @Configuration public class RedisConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { RestTemplate restTemplate = builder.build(); restTemplate.getMessageConverters().add( new MappingJackson2HttpMessageConverter()); return restTemplate; } } |
之后使用
1
2
|
@Autowired private RestTemplate restTemplate; |
直接正常使用就可以
1
2
|
String url = "http://localhost:8080/findById?id=1" ;//請求的地址 String request = restTemplate.getForObject(url, String. class ); |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_40667143/article/details/83444822