【问题标题】:Use HTTP response data within spring boot在 Spring Boot 中使用 HTTP 响应数据
【发布时间】:2021-02-21 15:48:43
【问题描述】:

我对 Spring Boot 和 Web 服务非常陌生。我实现了 Spring Boot 应用程序来将产品保存到数据库。它工作正常。现在我想使用产品价格进行一些计算。

例如,我有所有产品的单价。当用户从前端选择他想要购买的产品和单位数量时,我会将产品 ID 和单位数量传递给一个 API 方法,该方法将计算他想要支付的总金额。

我有以下方法可以根据产品ID获取产品详细信息。

@GetMapping("/products/{id}")
public ResponseEntity<Product> getProductById(@PathVariable(value = "id") Long productId)
    throws ResourceNotFoundException {
    Product product = productRepository.findById(productId)
      .orElseThrow(() -> new ResourceNotFoundException("Product not found for this id :: " + productId));
    return ResponseEntity.ok().body(product);
}

它给了我以下响应。

{ “身份证”:8, "name": "企鹅耳朵", “纸箱价格”:175, “单价”:9.0, "unitForCarton": 20 }

所以我想在另一个方法中使用这个 unitPrice。我该怎么做?

【问题讨论】:

  • 我认为你必须先看看设计。你的最终目标是计算价格,因为你已经提到你得到了响应,所以在另一个 api 方法中利用该值来计算项目价格。
  • @harry 是的,我想知道。如何在另一个 api 调用中使用一个 api 响应

标签: java spring spring-boot rest


【解决方案1】:

通常Controller 调用Service 层,其逻辑在需要时调用Repository 层。

因此,在您的情况下,您可以拥有一个 Service 类,其公共方法为 getProductById。 此方法返回一个对象。不是 JSON。

Controller 将调用此 service 类并将对象转换为 JSON。

您的新端点将调用Service 类中的另一个方法(可能是buyMe?)。

buyMe 是一个与getProductById 位于同一Service 中的方法。所以很容易从另一个方法调用一个方法。

【讨论】:

    【解决方案2】:

    你应该遵循的方式是:

    1. Controller
    2. Service
    3. Repository

    首先在Controller 中,我们负责端点并将工作委托给我们的Service。对于您的用例,我将使用DTO(数据传输对象)。基本上,您将一些不同的属性打包到一个 java POJO 中,如下所示:

    public class BuyEnquiryDto
    {
        private int productId; // You could also pack these into an array if you have several Products
        private int quantity;
    
        // Getters and setters
    }
    

    然后在控制器中:

    @Controller
    public class Controller
    {
        private ProductService productService;
        
        public Controller(ProductService productService)
        {
            this.productService = productService;
        }
    
        @GetMapping("/products/buyProduct")
        public ResponseEntity<Product> buyProduct(@RequestBody BuyEnquiryDto buyEnquiryDto )
        {
            return this.productService.buyProduct(buyEnquiryDto);
        }
    }
    

    然后我们就有了处理业务逻辑的服务:

    public class ProductService
    {
        private ProductRepo productRepo;
    
        public ResponseEntity<Product> buyProduct(BuyEnquiryDto buyEnquiryDto)
        {
            int productId = buyEnquiryDto.getProductId();
            
            productRepo.findById(productId).orElseThrow(...smth);
            
            /// Your logic continues here, you may also want to return something else, maybe the total price...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多