Spring Boot PUT接口Postman调用返回404 Not Found问题咨询
问题根因定位
共4个核心问题会触发接口返回404,按影响优先级排序:
- 接口路径重复配置
类级别已经配置@RequestMapping("/customer"),方法上的@PutMapping又写了/customer/{id},最终接口实际映射路径为/customer/customer/{id},如果Postman请求的是PUT /customer/{id},根本匹配不到接口映射,会直接返回404。 - Service层逻辑缺陷触发异常,被Controller捕获后统一返回404
- Spring Data JPA的
findById()返回值是Optional<Customer>类型,无论数据库是否存在对应数据,该方法永远不会返回null,原有代码写的if (cutomerRepository.findById(customer.getId()) != null)判断完全无效。如果查询不到对应ID的数据,后续调用.get()会抛出NoSuchElementException,被Controller层catch块捕获后返回404。 - Controller层通过
@PathVariable接收了路径上的id参数,但调用Service时完全没有传递该值,Service全程使用请求体CustomerDTO里的id字段,如果Postman请求体未传id、或者id值和路径参数不一致,就会触发查询异常返回404。 - invoices字段判断缺少空校验:如果请求体中
invoices字段为null,直接调用.size()会抛出空指针异常,同样会进入catch块返回404。 - 贴出的Service代码中if判断块外没有返回值,当查询不到对应客户时方法无合法返回值,会直接抛出运行时异常。
- Spring Data JPA的
- 变量拼写错误
代码中所有Repository变量名都拼成了cutomerRepository(正确拼写为customerRepository,少了字母s),如果变量名和实际注入的Repository Bean名称不匹配,会导致启动时依赖注入失败,接口无法正常映射。 - 异常捕获逻辑过于粗糙
Controller层把所有Exception都统一捕获返回404,无论是路径不匹配、空指针、数据库连接错误,全部返回404状态码,完全无法区分是接口不存在还是业务逻辑报错。
修复方案
- 修正接口路径配置,去掉重复的路径前缀,同时把路径参数id传给Service层,修正后Controller代码片段:
@RestController @RequestMapping("/customer") public class CustomerController { @Autowired CustomerServiceImpl customerService; // 去掉重复的/customer前缀 @PutMapping("/{id}") public ResponseEntity<Customer> updateCustomer(@PathVariable(value = "id") int id, @RequestBody CustomerDTO customer) { try{ // 传递路径id给Service,避免请求体id和路径id不一致 Customer newCustomer = customerService.updateCustomer(id, customer); return new ResponseEntity<>(newCustomer, HttpStatus.OK); }catch (Exception exception){ // 排查阶段可打印异常栈定位问题,上线后替换为日志输出 exception.printStackTrace(); // 不要所有异常都返回404,业务异常单独处理,系统异常返回500 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } }
- 重写Service层更新逻辑,正确使用Optional做存在性判断,修复空指针问题:
@Override @Transactional public Customer updateCustomer(int pathId, CustomerDTO customer) { // 以路径上的id为准查询,避免请求体篡改资源id Optional<Customer> customerOpt = customerRepository.findById(pathId); if (customerOpt.isEmpty()) { throw new IllegalArgumentException("指定ID的客户不存在"); } Customer persistenceCustomer = customerOpt.get(); if (customer.getEmail() != null) { persistenceCustomer.setEmail(customer.getEmail()); } if (customer.getMobileNumber() != null) { persistenceCustomer.setMobileNumber(customer.getMobileNumber()); } // 先判断invoices不为空,再判断长度,避免空指针 if (customer.getInvoices() != null && !customer.getInvoices().isEmpty()) { persistenceCustomer.setInvoices(customer.getInvoices()); } return customerRepository.save(persistenceCustomer); }
- 全局检查变量名拼写,修正
cutomerRepository为customerRepository,确保和注入的Bean名称匹配。 - Postman调用时确认请求路径为
PUT http://服务地址/customer/目标客户ID,请求头Content-Type设置为application/json,请求体为合法JSON格式。
额外排查点:如果修正路径后仍返回404,检查应用是否配置了
server.servlet.context-path,如果有配置,请求路径需要加上对应上下文前缀。
内容的提问来源于stack exchange,提问作者renad sahal
相关产品推荐
相关产品推荐

