今天写了一个Demo,发现默认创建完SpringBoot的web项目后,RestTemplate无法自动注入了,报如下异常:
Field restTemplate in org.xharvard.boot.controller.RestTempController 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)
查阅资料后,发现是官方去除了,原因如下:
If you need to call remote REST services from your application, you can use the Spring Framework’s RestTemplate class. Since
RestTemplate
instances often need to be customized before being used, Spring Boot does not provide any single auto-configuredRestTemplate
bean. It does, however, auto-configure aRestTemplateBuilder
, which can be used to createRestTemplate
instances when needed. The auto-configuredRestTemplateBuilder
ensures that sensibleHttpMessageConverters
are applied toRestTemplate
instances.
官网地址:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#io.rest-client.resttemplate
默认导入了RestTemplateBuilder,可以如下处理:
@Service
public class MyService {
private final RestTemplate restTemplate;
public MyService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
public Details someRestCall(String name) {
return this.restTemplate.getForObject("/{name}/details", Details.class, name);
}
}
restTemplateBuilder.build() 返回的即是 RestTemplate。