配置了GetMapping映射的Spring Boot项目访问接口返回404是什么原因?
Spring Boot访问/hello返回404问题原因及解决方案
核心原因
你的pom.xml中缺少Spring Boot Web场景的启动器依赖spring-boot-starter-web:
你当前仅单独引入了spring-web、spring-boot-starter-tomcat两个零散依赖,Spring Boot的Web自动配置逻辑(包含DispatcherServlet注册、请求映射解析、Controller接口扫描等核心功能)必须依赖spring-boot-starter-web触发,零散引入不会触发自动配置,导致你定义的@GetMapping("/hello")没有被Spring识别注册,所以访问时返回404。
修复方案
删除pom.xml中如下两个依赖:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <!--<scope>provided</scope>--> </dependency>
替换为官方Web场景启动器:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
修改后重新导入Maven依赖、重启项目即可,正常启动后可以在控制台看到请求映射注册日志:Mapped "{[/hello],methods=[GET]}",此时访问http://localhost:8080/hello就能正常返回结果。
其他可能排查方向
- 确认启动日志中Tomcat监听端口是否为8080,若配置了
server.port自定义端口,访问时需替换为对应端口 - 若配置了
server.servlet.context-path自定义上下文路径,访问地址需要添加上下文路径前缀,比如上下文路径为/demo时,访问地址为http://localhost:8080/demo/hello
内容的提问来源于stack exchange,提问作者Steven Armstrong
相关产品推荐
相关产品推荐

