问题类型的 create() 方法未定义

问题描述 投票:0回答:1

所以我尝试使用 Java 和 Spring 框架构建一个简单的 RESTful Api。我正在关注 https://spring.io/guides/tutorials/rest/ 的 Spring 文档。但是,我遇到了一个问题,即没有为“问题”类型定义方法“create()”。本教程的这一部分不显示如何导入“Problem”或方法“created()”来自何处。用于“问题”的导入可能不正确。

这里是在DeleteMapping 和PutMapping 中使用它的代码片段。我到处寻找,但没有找到关于如何解决此问题或使用什么导入的有用信息。谢谢。

//Current import for Problem
import org.springframework.beans.factory.parsing.Problem;
@DeleteMapping("/orders/{id}/cancel")
ResponseEntity<?> cancel(@PathVariable Long id) {

  Order order = orderRepository.findById(id) //
      .orElseThrow(() -> new OrderNotFoundException(id));

  if (order.getStatus() == Status.IN_PROGRESS) {
    order.setStatus(Status.CANCELLED);
    return ResponseEntity.ok(assembler.toModel(orderRepository.save(order)));
  }

  return ResponseEntity //
      .status(HttpStatus.METHOD_NOT_ALLOWED) //
      .header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) //
      .body(Problem.create() //
          .withTitle("Method not allowed") //
          .withDetail("You can't cancel an order that is in the " + order.getStatus() + " status"));
}
@PutMapping("/orders/{id}/complete")
ResponseEntity<?> complete(@PathVariable Long id) {

  Order order = orderRepository.findById(id) //
      .orElseThrow(() -> new OrderNotFoundException(id));

  if (order.getStatus() == Status.IN_PROGRESS) {
    order.setStatus(Status.COMPLETED);
    return ResponseEntity.ok(assembler.toModel(orderRepository.save(order)));
  }

  return ResponseEntity //
      .status(HttpStatus.METHOD_NOT_ALLOWED) //
      .header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) //
      .body(Problem.create() //
          .withTitle("Method not allowed") //
          .withDetail("You can't complete an order that is in the " + order.getStatus() + " status"));
}
java spring rest spring-mvc
1个回答
0
投票

是的,我也在 Spring 教程中偶然发现了这一点。幸运的是,我找到了一个简单的解决方法:只需更换

.body(Problem.create() //
                  .withTitle("Method not allowed") //
                  .withDetail("You can't cancel an order that is in the " + order.getStatus() + " status"));

.body("You can't cancel an order that is in the " + order.getStatus() + " status");

代码将被编译!

© www.soinside.com 2019 - 2024. All rights reserved.