How to autowire RestTemplate using annotations

2019-08-14
背景说明:

今天,在复用其他项目的模块时候,引入maven后启动报错:

Ddsription:
Field restTemplate in xxx.impl.xxServiceImpl required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.client.RestTemplate' in your configuration

问题很简单,就是你自动注入的bean没找到需要配置下呗。

原来的项目是配置在特定的地方,而模块里面并没有配置,引入模块,并未引入配置,因此需要配置bean:

@Configuration
public class CommonAutoConfiguration {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(5000);
        return factory;
    }
}

不同的设置参考 这里:How to autowire RestTemplate using annotations-stackOverflow