Spring Boot GET端点请求持续返回404错误如何解决
Spring Boot GET接口返回404排查方案
问题背景
开发Spring Boot应用时编写了GET类型接口,添加了@RestController与@GetMapping("/home")注解,请求接口时始终返回404状态码。
关联代码
StudentController.java:
package student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDate; import java.time.Month; import java.util.List; @RestController public class StudentController { @GetMapping("/home") public String home(){ return "This is String"; } }
项目结构

排查步骤&修复方案
该问题核心原因是控制器未被Spring上下文扫描加载,对应的接口映射没有注册到Web容器中,按以下优先级排查:
- 检查主启动类存放位置
Spring Boot默认组件扫描范围为@SpringBootApplication标注的主启动类所在包,及其所有子包。当前控制器存放在student包下,如果主启动类不在student包的上层根目录,Spring不会识别到该控制器。
推荐使用Spring官方标准项目结构,将主启动类放在所有业务代码包的根路径下:src/main/java └── 自定义根包(例:com.example.studentdemo) ├── StudentDemoApplication.java // 主启动类,位于根包 └── student // 业务子包 └── StudentController.java - 手动指定扫描范围(不调整结构时使用)
若不想修改现有目录结构,直接在主启动类的@SpringBootApplication注解上声明要扫描的包路径:@SpringBootApplication(scanBasePackages = "student") public class StudentDemoApplication { public static void main(String[] args) { SpringApplication.run(StudentDemoApplication.class, args); } } - 常规配置校验
- 项目启动后查看控制台日志,搜索
/home关键字,若没有出现Mapped "{[/home],methods=[GET]}"格式的映射日志,证明控制器未被成功加载 - 确认请求地址正确:默认服务端口为8080,无额外配置时完整请求地址为
http://localhost:8080/home - 检查项目配置文件,若配置了
server.servlet.context-path属性(例:值为/app),请求路径需要拼接对应前缀,即http://localhost:8080/app/home
- 项目启动后查看控制台日志,搜索
内容的提问来源于stack exchange,提问作者Usama Hameed
相关产品推荐
相关产品推荐

