我们常常在注入restTemplate对象时使用会报空的异常:
private RestTemplate restTemplate;
即restTemplate 对象没有注入到容器中来,所以会报空。
我们可以采用以下方式:
1.在启动类加一个Bean配置
@Autowired private RestTemplateBuilder builder; public static void main(String[] args) { @Bean public RestTemplate restTemplate() { return new RestTemplate(); }
2.RestTemplateConfig.clss文件,放在启动类同包下
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.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; }