You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按Spring官方教程开发REST API 访问/api/players返回404问题求助

问题排查与解决方法

1. 检查依赖完整性

Spring Data REST 自动暴露 Repository 为 REST 接口的能力依赖spring-boot-starter-data-rest组件,若漏加该依赖只会引入JPA能力,不会自动生成REST接口。请确认项目构建文件中已引入以下依赖:
Maven pom.xml示例:

<!-- 必须引入,否则不会自动生成REST接口 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 按需引入对应的数据库驱动 -->

2. 核对包扫描范围与Repository访问权限

Spring Boot 启动类的@SpringBootApplication注解默认仅扫描启动类所在包以及所有子包下的类,若你的Player实体类、PlayerRepository仓库类放到了启动类扫描范围外,Spring将无法识别对应组件,自然不会生成接口。

  • 推荐包结构如下,所有业务类都放在启动类的子包下:
com.yourpackage
├── Application.java (启动类)
├── entity
│   └── Player.java
├── repo
│   └── PlayerRepository.java
└── loader
    └── DatabaseLoader.java
  • 若无法调整包结构,可在启动类上主动指定扫描路径:
@SpringBootApplication
@EntityScan(basePackages = "替换为你的实体类所在包路径")
@EnableJpaRepositories(basePackages = "替换为你的Repository所在包路径")
@ComponentScan(basePackages = "替换为你的组件扫描根路径")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

同时确认PlayerRepository使用public修饰,非public的Repository默认不会被Spring Data REST识别。

3. 检查Spring Data REST配置

查看application.properties中是否有修改默认资源检测策略的配置:

  • 如果存在spring.data.rest.detection-strategy=annotated配置,说明仅加了@RepositoryRestResource注解的Repository才会被暴露为接口,要么删除该配置,要么给PlayerRepository加上@RepositoryRestResource注解即可。

4. 验证接口注册状态

启动项目时查看控制台输出的日志,搜索/api/players相关的映射记录,正常启动会输出类似RequestMappingHandlerMapping : Mapped "{[/api/players]...}的日志,若无该日志则说明上述配置仍有问题。

内容的提问来源于stack exchange,提问作者Tim Hudson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:06:01