RestTemplate加@Autowired注入不了
1、在启动类加入
如图箭头所示代码:

然后在进行@Autowired发现不报错了。
完美解决

SpringBoot 如何注入RestTemplate
创建一个文件夹 ,我这边习惯于创建config文件夹
将下面的一段代码放到里面
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;
}
}
之后使用
@Autowired private RestTemplate restTemplate;
直接正常使用就可以
String url = "http://localhost:8080/findById?id=1";//请求的地址 String request = restTemplate.getForObject(url, String.class);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。

- 本文固定链接: https://www.zxbcw.cn/post/220133/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)