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

IntelliJ创建的Spring Boot Hello REST API返回404错误求助

排查Spring Boot REST控制器404错误的方向与解决办法

以下是针对纯REST控制器场景的404问题排查步骤:

1. 检查主应用类的包扫描范围

Spring Boot默认只会扫描主启动类所在包及其子包下的组件。如果你的HelloController所在包不在主类的扫描范围内,控制器不会被加载。

  • 示例:若主启动类在com.example包下,而控制器在com.example.springboot包下(子包),没问题;若控制器在com.other.springboot包下,就会被遗漏。
  • 解决:要么将控制器移到主类所在包或其子包下,要么在主启动类上添加@ComponentScan指定扫描路径:
    @SpringBootApplication
    @ComponentScan("com.example.springboot") // 指定控制器所在包
    public class YourApplication {
        public static void main(String[] args) {
            SpringApplication.run(YourApplication.class, args);
        }
    }
    

2. 确认主启动类的核心注解

主启动类必须标注@SpringBootApplication,这个注解整合了@ComponentScan(组件扫描)、@EnableAutoConfiguration(自动配置WebMvc等组件)和@SpringBootConfiguration,缺少该注解会导致Web服务无法正确初始化。

3. 验证Web依赖是否正确引入

确保项目依赖中包含spring-boot-starter-web,它会自动引入Spring MVC、Tomcat等Web相关组件,没有这个依赖,请求无法被DispatcherServlet处理。

  • Maven(pom.xml):
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  • Gradle(build.gradle):
    implementation 'org.springframework.boot:spring-boot-starter-web'
    

4. 查看启动日志确认映射情况

启动应用时,检查控制台日志:

  • 确认是否存在类似Mapped "{[/]}" onto public java.lang.String com.example.springboot.HelloController.index()的日志,这条日志表示控制器方法已成功映射到根路径。
  • 确认Tomcat启动的端口,日志会显示Tomcat started on port(s): 8080 (http),如果端口不是8080,需用对应端口发起请求(如curl localhost:8081)。

5. 检查控制器注解的正确性

确保@RestController和@GetMapping导入的是Spring官方包:

  • @RestController → org.springframework.web.bind.annotation.RestController
  • @GetMapping → org.springframework.web.bind.annotation.GetMapping
    避免导入其他第三方包的同名注解,导致注解失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:20:30