Подтвердить что ты не робот

Не удалось создать поле autwire: RestTemplate в приложении загрузки Spring

Во время запуска при загрузке приложения spring во время запуска появляется следующее исключение:

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

Я запускаю RestTemplate в своем TestController. Я использую 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);
    }
}

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";
    }

}

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>
4b9b3361

Ответ 1

Это именно то, что говорит ошибка. Вы не создали ни одного RestTemplate bean, поэтому он не может автоопределить. Если вам нужен RestTemplate, вам нужно будет его предоставить. Например, добавьте следующее в TestMicroServiceApplication.java:

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

Обратите внимание, что в более ранних версиях Spring cloud starter для Eureka для вас был создан RestTemplate bean, но это уже не так.

Ответ 2

В зависимости от того, какие технологии вы используете и какие версии будут влиять на то, как вы определяете RestTemplate в своем классе @Configuration.

Spring> = 4 без Spring Boot

Просто определите @Bean:

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

Весенний ботинок <= 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;

Ссылка

Ответ 3

Если 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)

тогда @Autowired будет работать. При использовании

@SpringBootTest(webEnvironment=WebEnvironment.MOCK)

затем создайте TestRestTemplate, как это

private TestRestTemplate template = new TestRestTemplate();

Ответ 4

Ошибка указывает, что RestTemplate bean не определен в контексте и не может загрузить beans.

  • Определите bean для RestTemplate, а затем используйте
  • Использовать новый экземпляр RestTemplate

Если вы уверены, что для шаблона RestTemplate определен bean, для печати beans, которые доступны в контексте, загруженном приложением spring для загрузки

используйте следующее:
ApplicationContext ctx = SpringApplication.run(Application.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
    System.out.println(beanName);
}

Если это содержит bean по названию/типу, то все хорошо. Или иначе определите новый bean, а затем используйте его.

Ответ 5

Так как экземпляры RestTemplate часто должны быть настроены перед использованием, Spring Boot не предоставляет ни одну автоматическую конфигурацию RestTemplate bean.

RestTemplateBuilder предлагает правильный способ настройки и создания шаблона останова bean, например, для базовых auth или перехватчиков.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
                .basicAuthorization("user", "name") // Optional Basic auth example
                .interceptors(new MyCustomInterceptor()) // Optional Custom interceptors, etc..
                .build();
}

Ответ 6

Пожалуйста, убедитесь, что две вещи:

1- Используйте аннотацию @Bean вместе с методом.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}

2- Область применения этого метода должна быть публичной, а не частной.

Полный пример -

@Service
public class MakeHttpsCallImpl implements MakeHttpsCall {

@Autowired
private RestTemplate restTemplate;

@Override
public String makeHttpsCall() {
    return restTemplate.getForObject("https://localhost:8085/onewayssl/v1/test",String.class);
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}
}