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就开启负载均衡的能力;

猜你喜欢

转载自blog.csdn.net/goodjava2007/article/details/129954166
今日推荐