简体   繁体   English

Spring WebFlux - 不可转换类型; 无法投射“reactor.core.publisher.Mono”

[英]Spring WebFlux - Inconvertible types; cannot cast 'reactor.core.publisher.Mono'

I am using Spring Boot for my API.我正在为我的 API 使用 Spring 引导。 I am rewriting my API, to adopt the microservices architecture.我正在重写我的 API,以采用微服务架构。

I have 2 classes:我有 2 节课:

1) Product 1) 产品

2) Ingredient 2) 成分

My Code:我的代码:

Here is my Product class:这是我的产品class:

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

}

Here is my Ingredient class:这是我的成分class:

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

In the Product microservice, I am doing an API call to the Ingredient microservice:产品微服务中,我正在对成分微服务进行 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.
}

Here is the line where I get the error in the above method:这是我在上述方法中得到错误的行:

return myProduct.addProductIngredient((Ingredient) myProductComponentMono);

I am getting the following error:我收到以下错误:

Inconvertible types;不可转换的类型; cannot cast 'reactor.core.publisher.Mono<com.product.product.Entity.Ingredient>' to 'com.product.product.Entity.Ingredient'无法将“reactor.core.publisher.Mono<com.product.product.Entity.Ingredient>”转换为“com.product.product.Entity.Ingredient”

What is a possible solution to fix the above problem?解决上述问题的可能解决方案是什么?

Just use myProductComponentMono.block() instead of casting the retrieved mono to Ingredient , since your code in method myProduct.addProductIngredient(...) accept only an object of Ingredient .只需使用myProductComponentMono.block()而不是将检索到的 mono 转换为Ingredient ,因为您在方法myProduct.addProductIngredient(...)中的代码只接受 object 的Ingredient

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM