简体   繁体   中英

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

I am using Spring Boot for my API. I am rewriting my API, to adopt the microservices architecture.

I have 2 classes:

1) Product

2) Ingredient

My Code:

Here is my Product 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:

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:

// 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'

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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