Spring RESTful API开发报错:Problem类的create()方法未定义
解决Spring REST教程中Problem.create()方法未定义的问题
问题根源
你当前导入的org.springframework.beans.factory.parsing.Problem是Spring内部用于Bean定义解析的工具类,完全没有create()方法,和教程里用来生成RFC 7807标准问题详情的Problem不是同一个类,这就是报错的核心原因。
正确的类与导入路径
教程中使用的是Spring Framework 6+(对应Spring Boot 3.x)引入的ProblemDetail类,专门用于生成符合HTTP问题详情规范的响应体,正确导入路径为:
import org.springframework.http.ProblemDetail;
依赖版本检查
确保你的项目使用Spring Boot 3.x版本(ProblemDetail是Spring 6才新增的API)。如果用Maven,pom.xml里的web starter依赖需满足版本要求:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 版本至少为3.0.0及以上 --> </dependency>
修改代码适配API
ProblemDetail的API和教程里的链式调用略有不同,需调整返回问题详情的代码:
以cancel方法为例,修改后的代码:
@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))); } // 构建标准问题详情实例 ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.METHOD_NOT_ALLOWED); problemDetail.setTitle("Method not allowed"); problemDetail.setDetail("You can't cancel an order that is in the " + order.getStatus() + " status"); return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) .header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) .body(problemDetail); }
complete方法做同样的修改即可。
补充说明
教程里的Problem.create()写法可能是早期草稿或简化示例,实际Spring官方推荐使用ProblemDetail实现标准HTTP错误响应,它会自动兼容RFC 7807规范,返回的JSON格式也符合行业标准。
内容的提问来源于stack exchange,提问作者DaddyDaveDog
相关产品推荐
相关产品推荐

