跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Spring Data REST
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Spring Data REST = '''Spring Data REST''' 是 [[Spring Framework]] 生态中的一个模块,用于自动将 [[Spring Data]] 仓库(Repositories)暴露为 [[RESTful]] Web 服务。它减少了手动编写控制器(Controllers)的需求,使得开发者能够快速构建基于 HTTP 的数据访问层。 == 概述 == Spring Data REST 基于 [[HATEOAS]](Hypermedia as the Engine of Application State)原则,自动生成符合 REST 规范的 API。它支持 [[CRUD]](Create、Read、Update、Delete)操作,并提供分页、排序、搜索等功能。通过简单的配置,开发者可以将数据库实体(Entities)直接映射为 REST 资源。 === 核心特性 === * 自动生成 REST 端点(Endpoints) * 支持 [[HAL]](Hypertext Application Language)格式的响应 * 提供分页(Pagination)和排序(Sorting) * 支持自定义查询方法(Query Methods) * 与 [[Spring Security]] 集成,实现权限控制 == 快速入门 == 以下示例展示如何通过 Spring Data REST 暴露一个简单的实体。 === 1. 添加依赖 === 在 `pom.xml` 中添加 Spring Data REST 依赖: <syntaxhighlight lang="xml"> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> </syntaxhighlight> === 2. 定义实体和仓库 === 创建一个 `Book` 实体和对应的仓库接口: <syntaxhighlight lang="java"> @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; // Getters and Setters } public interface BookRepository extends JpaRepository<Book, Long> { } </syntaxhighlight> === 3. 访问 REST API === 启动应用后,Spring Data REST 会自动生成以下端点: * `GET /books` - 获取所有书籍(支持分页) * `GET /books/{id}` - 获取单个书籍 * `POST /books` - 创建新书籍 * `PUT /books/{id}` - 更新书籍 * `DELETE /books/{id}` - 删除书籍 示例请求和响应: <syntaxhighlight lang="bash"> # 创建书籍 curl -X POST -H "Content-Type: application/json" -d '{"title":"Spring in Action","author":"Craig Walls"}' http://localhost:8080/books # 响应 { "title": "Spring in Action", "author": "Craig Walls", "_links": { "self": { "href": "http://localhost:8080/books/1" }, "book": { "href": "http://localhost:8080/books/1" } } } </syntaxhighlight> == 高级功能 == === 自定义端点路径 === 通过 `@RepositoryRestResource` 注解修改默认路径: <syntaxhighlight lang="java"> @RepositoryRestResource(path = "library") public interface BookRepository extends JpaRepository<Book, Long> { } </syntaxhighlight> 此时端点变为 `/library`。 === 自定义查询方法 === 在仓库中声明方法,Spring Data REST 会自动生成对应的端点: <syntaxhighlight lang="java"> public interface BookRepository extends JpaRepository<Book, Long> { List<Book> findByAuthor(String author); } </syntaxhighlight> 访问方式:`GET /books/search/findByAuthor?author=Craig%20Walls` === 关联资源处理 === 如果实体有关联关系(如 `Book` 和 `Author`),Spring Data REST 会自动处理关联资源的 URI。例如: <syntaxhighlight lang="java"> @Entity public class Author { @Id @GeneratedValue private Long id; private String name; @OneToMany(mappedBy = "author") private Set<Book> books; } </syntaxhighlight> 访问作者的所有书籍:`GET /authors/1/books` == 实际案例 == 假设我们要构建一个在线书店系统,使用 Spring Data REST 可以实现以下功能: 1. 书籍管理(CRUD) 2. 按作者或标题搜索书籍 3. 分页浏览书籍列表 <mermaid> graph LR Client -->|HTTP请求| SpringDataREST SpringDataREST -->|调用| Repository Repository -->|操作| Database </mermaid> == 配置与优化 == === 启用/禁用特定仓库 === 在 `application.properties` 中配置: <syntaxhighlight lang="properties"> # 禁用默认暴露所有仓库 spring.data.rest.detection-strategy=annotated # 仅暴露带有 @RepositoryRestResource 的仓库 </syntaxhighlight> === 安全控制 === 与 Spring Security 集成示例: <syntaxhighlight lang="java"> @Configuration public class SecurityConfig { @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/books/**").hasRole("ADMIN") .anyRequest().authenticated() ); return http.build(); } } </syntaxhighlight> == 数学表示 == Spring Data REST 的核心功能可以抽象为: <math> f: (Repository, Configuration) \rightarrow \{REST\ Endpoints\} </math> 其中: * <math>Repository</math> 是 Spring Data 仓库接口 * <math>Configuration</math> 包括路径、分页大小等参数 * <math>\{REST\ Endpoints\}</math> 是生成的 REST 端点集合 == 注意事项 == * 对于复杂业务逻辑,仍需编写自定义控制器 * 默认开启的分页功能可能导致性能问题(可调整页面大小) * 生产环境应始终启用安全控制 == 总结 == Spring Data REST 极大简化了 REST API 的开发工作,特别适合快速原型开发和中小型项目。通过合理配置,可以构建出符合 REST 规范的、功能完善的 Web 服务,同时保持代码的简洁性。 [[Category:后端框架]] [[Category:Spring]] [[Category:Spring数据]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)