解决RestTemplate加@Autowired注入不了的问题
更新时间:2021年08月19日 11:43:33 作者:梦想注定是孤独的旅行
这篇文章主要介绍了解决RestTemplate加@Autowired注入不了的问题,具有很好的参考价值,希望对大家有所帮助。
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);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
使用Spring Boot Mybatis 搞反向工程的步骤
这篇文章主要介绍了使用Spring Boot Mybatis 搞反向工程的步骤,帮助大家更好的理解和使用spring boot框架,感兴趣的朋友可以了解下2021-01-01


最新评论