You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot Delete接口调用返回404错误求助(ID存在但无法删除)

SpringBoot REST API DELETE请求返回404问题排查

问题描述

我刚开始学习SpringBoot并开发首个REST API,已经成功实现GET和POST方法,但在实现Delete方法时遇到了问题。

相关代码

PersonService.java

@Service
public class PersonService {

    public void deletePersonById(Long id){
        System.out.println("Attempting to delete person with ID: " + id);
        personRepository.deleteById(id);
    }
}

PersonController.java

@RestController
@RequestMapping("/person")
public class PersonController {
    private final PersonService personService;

    public PersonController(PersonService personService){
        this.personService = personService;
    }

    @DeleteMapping("/delete/{id}")
    public void deletePersonById(@PathVariable Long id) {
        personService.deletePersonById(id);
    }

}

请求错误信息

调用DELETE请求 http://localhost:8080/person/delete/1 时,返回404错误:

{
  "timestamp": "2025-01-24T18:30:36.281+00:00",
  "status": 404,
  "error": "Not Found",
  "path": "/person/delete/1"
}

ID为1的用户确实存在,但无法定位问题所在。

配置文件(application.properties)

spring.application.name=Record 

# Database credentials 
spring.datasource.url=${DATABASE_URL}
spring.datasource.driver=org.h2.Driver
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}


# JPA / Hibernate configuration 
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.h2.console.enabled=true 

# Flyway configuration
spring.flyway.enable=true
spring.flyway.locations=classpath:db/migrations
spring.flyway.baseline-on-migrate=true

代码结构

我的代码结构

无ID访问的错误

若不指定ID访问Delete路由,会出现如下错误:
无ID访问Delete路由的错误


排查方案

  1. 确认控制器包扫描范围
    SpringBoot默认扫描启动类所在包及其子包。检查PersonController是否和启动类在同一包或子包下,若不在,在启动类添加@ComponentScan(basePackages = "控制器所在包路径")手动指定扫描范围。

  2. 验证请求方法和路径

    • 确保请求用的是DELETE方法,而非GET/POST,部分工具默认用GET会导致路由不匹配。
    • 核对路径拼写:/person/delete/1是否和@RequestMapping("/person") + @DeleteMapping("/delete/{id}")完全一致。
  3. 检查路径变量绑定
    尝试显式指定变量名:@PathVariable("id") Long id,避免编译参数问题导致绑定失败。

  4. 查看路由映射日志
    启动应用时,查看控制台是否有Mapping DELETE /person/delete/{id}的日志。如果没有,说明控制器未被Spring容器管理,检查@RestController注解是否遗漏,或包扫描是否正确。

  5. 排查Flyway迁移脚本
    确认Flyway迁移脚本正确创建了person表,且id字段类型与代码中Long匹配,避免数据类型不匹配导致的问题(虽然404更可能是路由问题)。

  6. 简化路由测试
    暂时将Delete路由改为@DeleteMapping("/{id}"),请求http://localhost:8080/person/1,验证是否能正常响应,排除路径层级过多的问题。


内容的提问来源于stack exchange,提问作者Chrystian Dybas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 17:40:04