在使用RestTemplate时,用@Autowired注入报错:

Could not autowire. No beans of 'RestTemplate' type found.

用@Resource注入虽然不报错了,但启动时报错:
A component required a bean of type 'org.springframework.web.client.RestTemplate' that could not be

经查阅资料发现,在 Spring Boot 1.3版本中,会默认提供一个RestTemplate的实例Bean,而在 Spring Boot 1.4以及以后的版本中,这个默认的bean不再提供了,因此我们需要手动创建一个RestTemplate的配置。

因此我们可以新建一个配置类RestTemplateConfig,代码如下:

@Configuration
public class RestTemplateConfig {
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

然后就可以运行成功了。

如果有兴趣了解更多相关内容,欢迎来我的个人网站看看:瞳孔的个人空间

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐