SpringBoot 2.7.9 RestController无法访问返回404问题求助
SpringBoot接口404问题解决
问题说明
SpringBoot应用已正常启动,8080端口服务状态正常,但通过Postman调用controller包中的RestController时返回404,请求地址为http://localhost:8080/api/product。尝试使用127.0.0.1、本机网络IP发起请求,问题依旧。
相关截图:
解决步骤
1. 修正包扫描范围
SpringBoot默认仅扫描主启动类所在包及其子包的组件。从截图可见,主启动类与Controller不在同一包层级,需手动指定扫描范围:
在主启动类上添加包扫描配置,示例代码:
@SpringBootApplication(scanBasePackages = {"你的主类包路径", "你的Controller包路径"}) public class ApplicationMain { public static void main(String[] args) { SpringApplication.run(ApplicationMain.class, args); } }
或者直接指定根包,覆盖所有需要扫描的子包:
@SpringBootApplication(scanBasePackages = "com.yourrootpackage")
2. 校验Controller注解与映射路径
- 确认Controller类标注的是
@RestController(若用@Controller需配合@ResponseBody才能返回接口数据) - 检查
@GetMapping("/api/product")(或对应请求方法注解)的路径拼写是否与请求地址完全一致,注意大小写、斜杠等细节
3. 查看启动日志确认映射
启动应用时查看控制台日志,若存在Mapped "{/api/product}" onto public ...的日志,说明接口映射成功;若无此日志,证明Controller未被Spring容器加载。
4. 检查上下文路径配置
若配置了server.servlet.context-path,请求地址需加上该前缀。例如配置server.servlet.context-path=/demo,则请求地址应为http://localhost:8080/demo/api/product
内容的提问来源于stack exchange,提问作者Pran Sukh
相关产品推荐
相关产品推荐



