Java 如何使用注释自动装配 RestTemplate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28024942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:28:11  来源:igfitidea点击:

How to autowire RestTemplate using annotations

javaspringspring-mvcresttemplate

提问by meeti sharma

When I try to autowire Spring RestTemplate, I am getting following error:

当我尝试自动装配 Spring 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.

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.

Using Spring 4 in an annotation driven environment.

在注解驱动的环境中使用 Spring 4。

My dispatcher servlet is configured as follows:

我的调度程序 servlet 配置如下:

<context:component-scan base-package="in.myproject" />
<mvc:default-servlet-handler />    
<mvc:annotation-driven />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

My class in which I am trying to autowire RestTemplate is as follows:

我尝试自动装配 RestTemplate 的课程如下:

@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);


    }
}

回答by riship89

@Autowired
private RestOperations restTemplate;

You can only autowire interfaces with implementations.

您只能使用实现自动装配接口。

回答by Brice McIver

If you're using Spring Boot 1.4.0 or later as the basis of your annotation-driven, Spring doesn't provides a single auto-configured RestTemplate bean. From their documentation:

如果您使用 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

https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/html/boot-features-restclient.html

If you need to call remote REST services from your application, you can use Spring Framework's RestTemplate class. Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances.

如果需要从应用程序调用远程 REST 服务,可以使用 Spring Framework 的 RestTemplate 类。由于 RestTemplate 实例在使用前经常需要自定义,因此 Spring Boot 不提供任何单个自动配置的 RestTemplate bean。然而,它会自动配置一个 RestTemplateBuilder,它可以在需要时用于创建 RestTemplate 实例。自动配置的 RestTemplateBuilder 将确保将合理的 HttpMessageConverters 应用于 RestTemplate 实例。

回答by eaykin

You can add the method below to your class for providing a default implementation of RestTemplate:

您可以将下面的方法添加到您的类中,以提供 RestTemplate 的默认实现:

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

回答by dustin.schultz

Errors you'll see if a RestTemplateisn't defined

如果 aRestTemplate未定义,您将看到的错误

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

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

or

或者

No qualifying bean of type [org.springframework.web.client.RestTemplate] found

找不到 [org.springframework.web.client.RestTemplate] 类型的合格 bean

How to define a RestTemplatevia annotations

如何定义一个RestTemplatevia注解

Depending on which technologies you're using and what versions will influence how you define a RestTemplatein your @Configurationclass.

根据您使用的技术和版本将影响您RestTemplate@Configuration类中定义 a的方式。

Spring >= 4 without Spring Boot

Spring >= 4 没有 Spring Boot

Simply define an @Bean:

简单地定义一个@Bean

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

Spring Boot <= 1.3

弹簧靴 <= 1.3

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

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

Spring Boot >= 1.4

弹簧靴 >= 1.4

Spring Boot no longer automatically defines a RestTemplatebut instead defines a RestTemplateBuilderallowing you more control over the RestTemplatethat gets created. You can inject the RestTemplateBuilderas an argument in your @Beanmethod to create a RestTemplate:

Spring Boot 不再自动定义 aRestTemplate而是定义 aRestTemplateBuilder允许您更好地控制RestTemplate创建的 。您可以RestTemplateBuilder在您的@Bean方法中作为参数注入来创建一个RestTemplate

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here
   return builder.build();
}

Using it in your class

在你的课堂上使用它

@Autowired
private RestTemplate restTemplate;

or

或者

@Inject
private RestTemplate restTemplate;

回答by Molay

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

回答by Abhinav Singhal

Add the @Configurationannotation in the RestTemplateSOMENAME which extends the RestTemplate class.

@Configuration在扩展 RestTemplate 类的 RestTemplateSOMENAME 中添加注释。

@Configuration         
public class RestTemplateClass extends RestTemplate {

}

Then in your controller class you can use the Autowired annotation as follows.

然后在您的控制器类中,您可以使用 Autowired 注释,如下所示。

@Autowired   
RestTemplateClass restTemplate;