如何使用注释自动装配 RestTemplate [英] How to autowire RestTemplate using annotations

查看:114
本文介绍了如何使用注释自动装配 RestTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试自动装配 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 有资格作为自动装配候选这个依赖.

在注释驱动的环境中使用 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 未定义,您将看到的错误

Errors you'll see if a RestTemplate isn't defined

考虑定义一个类型的bean'org.springframework.web.client.RestTemplate' 在您的配置中.

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

取决于您使用的技术以及哪些版本会影响您在 @Configuration 类中定义 RestTemplate 的方式.

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

简单地定义一个@Bean:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Spring Boot <= 1.3

不需要定义一个,Spring Boot 会自动为你定义一个.

No need to define one, Spring Boot automatically defines one for you.

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();
}

在课堂上使用它

@Autowired
private RestTemplate restTemplate;

@Inject
private RestTemplate restTemplate;

这篇关于如何使用注释自动装配 RestTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆