...中构造函数的参数0需要找不到类型为'org.springframework.web.client.RestTemplate'的bean

时间:2019-11-29 04:49:36

标签: java spring spring-cloud netflix-eureka

我无法运行从链接“ https://developers.ascendcorp.com/สร้าง-microservices-ด้วย-netflix-oss-และ-spring-cloud-2678667d9dbc”中学到的应用程序

当我运行应用程序时,它显示' com.krittawat.productservice.controller.ProductController中的构造函数的参数0,要求找不到类型为'org.springframework.web.client.RestTemplate'的bean。 ”。

我的代码: 控制器:

package com.krittawat.productservice.controller;

import com.krittawat.productservice.model.Product;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping(value = "products")
public class ProductController {
    private final RestTemplate restTemplate;

    @Autowired
    public ProductController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/search")
    public Product getProductsByTypeAndName(@RequestParam(value = "sku") final String sku) {
        String url = "http://PRICING-SERVICE/products/price?sku=" + sku;
        return restTemplate.getForObject(url, Product.class);
    }
}

型号:

package com.krittawat.productservice.model;

import lombok.Data;

@Data
public class Product {
    private String sku;
    private String price;
}

主要应用:

@SpringBootApplication
@EnableDiscoveryClient
public class ProductServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProductServiceApplication.class, args);
    }

}

2 个答案:

答案 0 :(得分:2)

在Configuration类中创建Rest模式的bean,如下所示

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

然后在您要使用的任何地方自动接线。

@Autowired
private RestTemplate restTemplate;

答案 1 :(得分:2)

其余模板用于创建使用RESTful Web服务的应用程序。您应该声明一个用于Rest Template的Bean,以自动连接Rest Template对象:

@Configuration
public class RestClientConfiguration {

    // First Method: default
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
    
    // Second Method: Using RestTemplateBuilder
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}

您也可以在SpringBootApplication类中声明它:

@SpringBootApplication
public class MyApplication {
   public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
   }
   @Bean
   public RestTemplate getRestTemplate() {
      return new RestTemplate();
   }
}