Spring Boot REST API DELETE接口报错及删除后返回对象问题求助
问题根因
你遇到的500错误核心来自两点:
- 增强for循环(for-each)遍历集合时直接调用
List.remove()方法,会触发ConcurrentModificationException异常,这是Java集合迭代的内置保护机制,只要遍历过程中集合结构被修改就会抛出该异常。 - 你当前的删除逻辑默认返回全量课程列表,和你需要返回被删除对象的需求不匹配。
修复代码
1. 调整CourseService接口定义
先将deleteCourse方法的返回值从List<Course>改为Course,用于返回被删除的课程对象:
public interface CourseService { // 其余原有方法不变 Course deleteCourse(long courseId); }
2. 重写服务层删除逻辑
改用迭代器安全删除,同时记录被删除的对象返回:
@Override public Course deleteCourse(long courseId) { Course deletedCourse = null; Iterator<Course> iterator = list.iterator(); while (iterator.hasNext()) { Course course = iterator.next(); if (course.getId() == courseId) { deletedCourse = course; iterator.remove(); // 迭代器自带的remove方法不会触发并发修改异常 break; } } return deletedCourse; }
3. 调整控制层删除接口
修改返回值类型匹配服务层:
@DeleteMapping("/courses/{courseId}") public Course deleteCourse(@PathVariable String courseId) { return this.courseService.deleteCourse(Long.parseLong(courseId)); }
可选优化(符合REST规范)
如果删除不存在的课程ID,当前会返回null,你可以调整控制层返回对应的404状态码,更符合接口设计规范:
@DeleteMapping("/courses/{courseId}") public ResponseEntity<Course> deleteCourse(@PathVariable String courseId) { Course deletedCourse = this.courseService.deleteCourse(Long.parseLong(courseId)); if (deletedCourse == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(deletedCourse, HttpStatus.OK); }
内容的提问来源于stack exchange,提问作者Ryuk
相关产品推荐
相关产品推荐

