【问题标题】:Spring WebFlux - Inconvertible types; cannot cast 'reactor.core.publisher.Mono'Spring WebFlux - 不可转换的类型;无法投射“reactor.core.publisher.Mono”
【发布时间】:2021-05-21 14:55:48
【问题描述】:

我正在为我的 API 使用 Spring Boot。我正在重写我的 API,以采用微服务架构。

我有 2 节课:

1) 产品

2) 成分

我的代码:

这是我的产品类:

    public class Product{
       private String name;
       @OneToMany
       private List<Ingredient> productIngredients; //Ingredient
       private Double quantity = 0.0;
       private Double productCost = 0.0;
       public void addIngredient(Ingredient myIngredient){
               this.productComponents.add(myIngredient);
       }

}

这是我的Ingredient类:

public class Ingredient{    
     private String name;
     private String unit;
     private Double quantity = 0.0;
}

Product 微服务中,我正在对 Ingredient 微服务进行 API 调用:

// Making a call to the Ingredients microservice from the product microservice

WebClient myWebClient = WebClient.create("http://localhost:8090/api");

@PostMapping("/component/list/add/{id}")
public Mono<Ingredient> addProductComponent(@PathVariable Long id){
      Product myProduct = new Product();
      Mono<Ingredient> myProductComponentMono =
                myWebClient
                        .get()
                        .uri("/components/component/get/{"+ id +'}')
                        .retrieve()
                        .bodyToMono(Ingredient.class);
    return myProduct.addProductIngredient((Ingredient) myIngredientMono); //this is the line where I am getting the error.
}

这是我在上述方法中得到错误的行:

return myProduct.addProductIngredient((Ingredient) myProductComponentMono);

我收到以下错误:

不可转换的类型;无法将 'reactor.core.publisher.Mono' 转换为 'com.product.product.Entity.Ingredient'

解决上述问题的可能解决方案是什么?

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-data-jpa


    【解决方案1】:

    只需使用myProductComponentMono.block() 而不是将检索到的单声道转换为Ingredient,因为您在方法myProduct.addProductIngredient(...) 中的代码只接受Ingredient 的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2011-08-11
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      相关资源
      最近更新 更多