新建Spring Boot Web应用接口无法访问问题求助
解决Spring Boot接口404问题的排查步骤
1. 检查启动类的包扫描范围
Spring Boot默认只会扫描启动类所在包及其子包下的组件。你的控制器位于controller包,而项目group为temp,如果启动类在temp包(比如temp.DemoApplication),那么controller包与temp包是同级关系,不在默认扫描范围内。
解决方法:
- 方法一:将控制器类移动到
temp.controller包下(推荐,符合Spring Boot默认规范) - 方法二:在启动类上添加
@ComponentScan注解,指定扫描包:@SpringBootApplication @ComponentScan(basePackages = {"temp", "controller"}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
2. 确保控制器响应类型正确
使用@Controller时,方法返回的字符串默认会被解析为视图名称(比如寻找yes.html页面),而非直接返回字符串内容。即便你试过@RestController仍404,大概率是包扫描问题,但仍需确认:
- 替换为
@RestController(等同于@Controller + @ResponseBody),或在test()方法上添加@ResponseBody注解:@RestController public class RepositoriesController { @GetMapping @CrossOrigin public String test(){ return "yes"; } }
3. 验证接口映射是否注册成功
启动项目后查看控制台日志,寻找类似以下的输出:
Mapped "{[/], GET}" onto public java.lang.String controller.RepositoriesController.test()
如果没有这条日志,说明控制器未被Spring容器扫描到,回到第一步检查包扫描配置。
4. 确认访问路径与端口正确
- 项目默认启动端口为8080,确保访问地址是
http://localhost:8080/ - 如果启用类级
@RequestMapping("github/v1"),访问路径需改为http://localhost:8080/github/v1
内容的提问来源于stack exchange,提问作者Raikiri13
相关产品推荐
相关产品推荐

