如何使用注释自动装配RestTemplate [英] How to autowire RestTemplate using annotations
问题描述
当我尝试自动装配Spring RestTemplate时,我收到以下错误:
When I try to autowire Spring RestTemplate, I am getting following error:
嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException :找不到类型为[org.springframework.web.client.RestTemplate]的限定bean依赖:预期至少有1个bean符合此依赖关系的autowire候选者。
在注释驱动的环境中使用Spring 4.
Using Spring 4 in an annotation driven environment.
我的调度程序servlet配置如下:
My dispatcher servlet is configured as follows:
<context:component-scan base-package="in.myproject" />
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
我尝试自动装配RestTemplate的课程如下:
My class in which I am trying to autowire RestTemplate is as follows:
@Service("httpService")
public class HttpServiceImpl implements HttpService {
@Autowired
private RestTemplate restTemplate;
@Override
public void sendUserId(String userId){
MultiValueMap<String, String> 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。
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
或
没有
类型的限定bean [org .springframework.web.client.RestTemplate]发现
No qualifying bean of type [org.springframework.web.client.RestTemplate] found
如何定义 RestTemplate
通过注释
取决于您使用的技术以及将影响您如何定义 RestTemplate
在 @Configuration
类中。
Depending on which technologies you're using and what versions will influence how you define a RestTemplate
in your @Configuration
class.
Spring> = 4没有Spring Boot
Spring >= 4 without Spring Boot
只需定义 @Bean
:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
Spring Boot< = 1.3
Spring Boot <= 1.3
无需定义一个,Spring Boot会自动为您定义一个。
No need to define one, Spring Boot automatically defines one for you.
Spring Boot> = 1.4
Spring Boot >= 1.4
Spring Boot不再自动定义 RestTemplate
但是定义了一个 RestTemplateBuilder
,允许您更多地控制创建的 RestTemplate
。您可以在 @Bean
方法中将 RestTemplateBuilder
作为参数注入,以创建 RestTemplate
:
Spring Boot no longer automatically defines a RestTemplate
but instead defines a RestTemplateBuilder
allowing you more control over the RestTemplate
that gets created. You can inject the RestTemplateBuilder
as an argument in your @Bean
method to create a RestTemplate
:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
// Do any additional configuration here
return builder.build();
}
在课堂上使用
Using it in your class
@Autowired
private RestTemplate restTemplate;
或
@Inject
private RestTemplate restTemplate;
这篇关于如何使用注释自动装配RestTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!