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

Spring Boot REST API端点无法访问,请求排查404问题

排查Spring Boot REST API 404问题的核心要点

刚看了你的问题,帮你梳理几个关键的问题点和修复步骤:

1. spring.data.rest.basePath 不作用于自定义@RestController

你配置的spring.data.rest.basePath=/micro是给Spring Data REST(比如自动生成的JPA Repository接口)用的,完全不会影响你自己写的@RestController。所以你的接口实际路径就是/something,对应访问地址是localhost:8081/something,而非带/micro的路径。

2. 主类存在语法错误,导致项目无法正常加载控制器

你的主类代码漏掉了类定义的大括号,正确写法应该是:

@SpringBootApplication
public class SpringBootRestExampleApplication { // 这里缺失的{必须补上
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestExampleApplication.class, args);
    }
}

这个语法错误会让项目启动异常,或者Spring无法扫描到你的控制器,直接引发404。

3. 控制器类名与注解同名,可能引发组件扫描冲突

你的控制器类名叫RestController,和Spring的@RestController注解完全同名,这会干扰Spring的组件扫描逻辑,建议改成更清晰的类名,比如SomethingRestController:

@RestController
public class SomethingRestController {
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, value = "/something")
    public Something getSomething(){
        Something s = new Something();
        return s;
    }
}

另外,@RestController已经自带了@ResponseBody的功能,方法上的@ResponseBody可以直接省略。

4. 确保Something模型类有正确的getter方法

如果Something类没有公共的getter方法,Spring在序列化JSON时会失败,甚至返回空内容或异常。示例写法:

public class Something {
    private String content;
    
    // 必须提供getter才能让Spring序列化字段
    public String getContent() {
        return content;
    }
    
    // 可选setter
    public void setContent(String content) {
        this.content = content;
    }
}

5. 确认组件扫描范围

如果你的控制器类不在主类的同级或子包下,Spring默认的组件扫描不会找到它。比如主类在com.example包,控制器在com.other.controller,就需要在主类上添加@ComponentScan(basePackages = "com.other")指定扫描路径。

验证步骤

  1. 先修复主类语法错误,启动项目后查看日志,如果你看到类似Mapped "{[/something],methods=[GET],produces=[application/json]}"的日志,说明控制器映射成功。
  2. 访问localhost:8081/something,此时应该能返回Something对应的JSON内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:13:14