怎么解决RestTemplate加@Autowired注入不了的问题
本篇内容介绍了“怎么解决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);
“怎么解决RestTemplate加@Autowired注入不了的问题”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!