Spring Boot REST Controller 出现Whitelabel Error Page 404问题求助
问题排查与解决方案
我帮你找到问题根源了!出现404的核心原因是Spring Boot的自动组件扫描范围没有覆盖到你的TopicController所在的包,导致控制器没有被注册到Spring容器中,自然无法处理/topic的请求。
为什么会这样?
你的启动类CourseApiApp位于spring.boot.api包下,而TopicController、TopicService和Topic实体类都在spring.boot.topic包下——这两个包是同级关系。Spring Boot默认只会自动扫描启动类所在的包以及它的子包,所以spring.boot.topic下的所有组件都没被Spring识别到。
三种解决办法,任选其一即可:
方法1:调整包结构(推荐,符合Spring Boot最佳实践)
把spring.boot.topic包修改为spring.boot.api.topic,让它成为启动类所在包spring.boot.api的子包。这样Spring Boot启动时会自动扫描到所有组件,不需要额外配置。
方法2:在启动类上添加@ComponentScan注解
手动指定需要扫描的包,把spring.boot.topic加入扫描范围:
package spring.boot.api; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan({"spring.boot.api", "spring.boot.topic"}) // 同时扫描api和topic包 // 或者直接扫描父包,更简洁:@ComponentScan("spring.boot") public class CourseApiApp { public static void main(String[] args) { SpringApplication.run(CourseApiApp.class, args); } }
方法3:使用@SpringBootApplication的scanBasePackages属性
在启动类的@SpringBootApplication注解里直接指定扫描的基础包:
package spring.boot.api; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = "spring.boot") public class CourseApiApp { public static void main(String[] args) { SpringApplication.run(CourseApiApp.class, args); } }
验证修改是否生效
重启应用后,访问localhost:8080/topic,应该能看到返回的JSON数据:
[{"id":"spring","name":"Spring Framework","description":"Spring Framework Description"},{"id":"Java","name":"Java Core","description":"Java Core Description"}]
同时可以观察控制台日志,启动时会出现类似这样的日志,说明控制器映射成功:
o.s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/topic]}" onto public java.util.List<spring.boot.topic.Topic> spring.boot.topic.TopicController.getAllTopics()
额外检查点(确保万无一失)
- 确认
TopicController上的@RestController、TopicService上的@Service注解都正确添加 - 确认
pom.xml里的spring-boot-starter-web依赖已经正确引入(你的配置没问题) - 确认应用确实在8080端口启动(控制台日志显示
Tomcat started on port(s): 8080 (http),没问题)
内容的提问来源于stack exchange,提问作者Sparsh Verma
相关产品推荐
相关产品推荐

