无法自动装配字段:Spring启动应用程序中的RestTemplate

Khu*_*uzi 86 spring maven resttemplate spring-boot

在启动期间运行spring boot应用程序时,我遇到异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.client.RestTemplate com.micro.test.controller.TestController.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. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Run Code Online (Sandbox Code Playgroud)

我在TestController中自动装配RestTemplate.我正在使用Maven进行依赖管理.

TestMicroServiceApplication.java

package com.micro.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestMicroServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestMicroServiceApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

TestController.java

    package com.micro.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value="/micro/order/{id}",
        method=RequestMethod.GET,
        produces=MediaType.ALL_VALUE)
    public String placeOrder(@PathVariable("id") int customerId){

        System.out.println("Hit ===> PlaceOrder");

        Object[] customerJson = restTemplate.getForObject("http://localhost:8080/micro/customers", Object[].class);

        System.out.println(customerJson.toString());

        return "false";
    }

}
Run Code Online (Sandbox Code Playgroud)

的pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.micro.test</groupId>
    <artifactId>Test-MicroService</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Test-MicroService</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
Run Code Online (Sandbox Code Playgroud)

g00*_*00b 133

这正是错误所说的.你没有创建任何RestTemplatebean,所以它不能自动装配任何bean.如果你需要,RestTemplate你必须提供一个.例如,将以下内容添加到TestMicroServiceApplication.java:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}
Run Code Online (Sandbox Code Playgroud)

请注意,在Eureka的早期版本的Spring云启动器中,RestTemplate为您创建了一个bean,但这不再适用.

  • 上调问题和你的答案原因当你为神奇地创造并链接其他所有内容时,你必须手动创建一个`RestTemplate`并不明显.特别是如果使用spring-cloud之前提供了自动配置的"RestTemplate".;-) (16认同)
  • 只是一个更新.从Spring Boot 1.4.0开始,`RestTemplateBuilder`可用于管理`RestTemplate`实例.这里的示例https://spring.io/guides/gs/consuming-rest/ (3认同)
  • 老实说,这就是我把这个问题放在论坛中的原因.我期待RestTemplate与我联系.:-)当我在POM.xml中包含Eureka依赖时,这工作正常.没有定义RestTemplate bean,它工作正常.尤里卡的一个类可能已经定义了这个bean. (2认同)

Sah*_*bra 23

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

Spring> = 4没有Spring Boot

只需定义一个@Bean:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

在课堂上使用它

@Autowired
private RestTemplate restTemplate;
Run Code Online (Sandbox Code Playgroud)

参考


小智 8

  • 你必须添加 @Bean public RestTemplate restTemplate(RestTemplateBuilder builder){ return builder.build(); }


小智 7

如果TestRestTemplate是单元测试中的有效选项,则此文档可能是相关的

http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-rest-templates-test-utility

简答:如果使用

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

然后@Autowired会工作.如果使用

@SpringBootTest(webEnvironment=WebEnvironment.MOCK)
Run Code Online (Sandbox Code Playgroud)

然后像这样创建一个TestRestTemplate

private TestRestTemplate template = new TestRestTemplate();
Run Code Online (Sandbox Code Playgroud)


小智 6

您正在尝试注入restTemplate,但您需要创建配置类。然后您需要创建返回新 RestTemplate 的 bean,请参阅下面的示例。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class YourConfigClass {


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

}
Run Code Online (Sandbox Code Playgroud)