欢迎光临
我们一直在努力

Springboot提示No beans of 'RestTemplate' type found错误

错误信息

在使用RestTemplate时,IntelliJ Idea提示Could not autowire. No beans of 'RestTemplate' type found.

代码清单:

@Component
public class SmsUtil {
    @Autowired
    private RestTemplate restTemplate;

}

出错原因

SpringBoot不再自动定义RestTemplate,而是需要自己手动定义。

解决办法

根据使用的技术及引入Spring以来的版本不同,解决方法可能有所差异。

1.Spring版本大于4的非Springboot框架

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

2.Springboot版本小于或等于1.3

无需定义RestTemplate依赖,Springboot已自动定义好。

3.Springboot版本大于或等于1.4

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}

修改后代码清单:

@Component
public class SmsUtil {
    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }
}

Reference:

  1. Could not autowire field:RestTemplate in Spring boot application
赞(0) 打赏
未经允许不得转载:Ddmit » Springboot提示No beans of 'RestTemplate' type found错误

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册