SpringBoot - 集成RestTemplate模板(十) - 使用过程中遇到找不到RestTemplate实例的错误

错误描述

Description:
Field restTemplate in com.hadoopx.quartz.executor.ServicexExecutor required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

错误分析

因为在 SpringBoot-1.3 及以前的版本中,会默认提供一个RestTemplate的实例BEAN,而在SpringBoot-1.4及以后的版本中,这个默认的BEAN不再提供。

解决方案 ①:
// 创建一个配置类, 在配置类中手动注入RestTemplate对象。
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 连接超时
        factory.setConnectTimeout(15000);
        // 数据读取超时时间
        factory.setReadTimeout(5000);
        return factory;
    }
}
解决方案 ②:
// 在 SpringBoot 项目启动类的Application 中,手动注入RestTemplate对象。
@Bean
// Spring Cloud的注解, 有该注解则RestTemplate就开启负载均衡能力, 也可以没有该注解。
@LoadBalanced
RestTemplate restTemplate(){
   return new RestTemplate();
}

知识延伸

  1. @LoadBalanced注解在org.springframework.cloud.client.loadbalancer包下;
  2. 在手动注入RestTemplate,一般会添加该注解,表示添加了该注解的RestTemplate就开启负载均衡的能力;
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cloneme01

谢谢您的支持与鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值