如何使用注释自动assemblyRestTemplate
当我尝试自动assemblySpring RestTemplate时,我收到以下错误:
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
在注释驱动的环境中使用Spring 4。
我的调度程序servlet配置如下:
我尝试自动assemblyRestTemplate的课程如下:
@Service("httpService") public class HttpServiceImpl implements HttpService { @Autowired private RestTemplate restTemplate; @Override public void sendUserId(String userId){ MultiValueMap map = new LinkedMultiValueMap(); map.add("userId", userId); map.add("secretKey", "kbhyutu7576465duyfy"); restTemplate.postForObject("http://localhost:8081/api/user", map, null); } }
如果RestTemplate
您将看到错误
考虑在配置中定义类型为’org.springframework.web.client.RestTemplate’的bean。
要么
找不到[org.springframework.web.client.RestTemplate]类型的限定bean
如何通过注释定义RestTemplate
取决于您使用的技术以及哪些版本将影响您在@Configuration
类中定义RestTemplate
。
Spring> = 4没有Spring Boot
只需定义一个@Bean
:
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
Spring Boot <= 1.3
无需定义一个,Spring Boot会自动为您定义一个。
Spring Boot> = 1.4
Spring Boot不再自动定义RestTemplate
,而是定义RestTemplateBuilder
允许您更好地控制创建的RestTemplate
。 您可以将RestTemplateBuilder
作为参数注入@Bean
方法以创建RestTemplate
:
@Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { // Do any additional configuration here return builder.build(); }
在课堂上使用它
@Autowired private RestTemplate restTemplate;
要么
@Inject private RestTemplate restTemplate;
您可以将以下方法添加到您的类中,以提供RestTemplate的默认实现:
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
如果您使用Spring Boot 1.4.0或更高版本作为注释驱动的基础,则Spring不提供单个自动配置的RestTemplate bean。 从他们的文件:
https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/html/boot-features-restclient.html
如果需要从应用程序调用远程REST服务,可以使用Spring Framework的RestTemplate类。 由于RestTemplate实例在使用之前通常需要进行自定义,因此Spring Boot不提供任何单个自动配置的RestTemplate bean。 但是,它会自动配置RestTemplateBuilder,可用于在需要时创建RestTemplate实例。 自动配置的RestTemplateBuilder将确保将合理的HttpMessageConverters应用于RestTemplate实例。
@Autowired private RestOperations restTemplate;
您只能通过实现自动连接接口。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateClient { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }