前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot:Data Rest Service

Spring Boot:Data Rest Service

作者头像
阿杜
发布2018-08-06 14:16:29
9150
发布2018-08-06 14:16:29
举报
文章被收录于专栏:阿杜的世界阿杜的世界

在文章RESTful by Spring Boot with MySQL通过在Controller中引入BookRepository来对外提供REST API。Spring Boot还可以通过spring-boot-starter-data-rest来对外提供REST API,可以免于编写对应的Controller,且具备分页和排序的功能。

实践

  • 在pom文件中添加依赖项
<dependency>
     <groupId>org.springframework.boot</groupId>      
     <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
  • 在包com.test.bookpub.repository下创建AuthorRepository接口,该接口继承自PagingAndSortingRepository,并用@RepositoryRestResource注解修饰。代码如下:
package com.test.bookpub.repository;

import com.test.bookpub.domain.Author;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface AuthorRepository
 extends PagingAndSortingRepository<Author, Long> {
}
  • 可以看出,实际编写的代码很少,同样套路,为Publisher和Reviewer也添加类似的接口。 PublisherRepository的代码如下:
package com.test.bookpub.repository;

import com.test.bookpub.domain.Publisher;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResourcepublic
interface PublisherRepository
    extends PagingAndSortingRepository<Publisher, Long> {
}

ReviewerRepository的代码如下:

package com.test.bookpub.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.test.bookpub.domain.Publisher.Reviewer;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResourcepublic interface ReviewerRepoistory
    extends PagingAndSortingRepository<Reviewer, Long> {
}
  • 启动应用程序,并访问http://localhost:8080/authors,将会得到如下结果

访问author信息

分析

显然,通过继承PagingAndSortingRepository接口,比直接写Controller能提供更多的功能:分页查询和对查询结果排序。

@RepositoryRestResource注解让编程人员可以直接通过repository提供数据接口,在这个“前端负责V和C,后端负责提供数据”的时代,非常方便;并且,可以通过给该注解传入参数来改变URL。

只要在项目的classpath中包含spring-boot-starter-data-rest,同时就包含了spring-hateoas库支持,这个库可以提供ALPS元数据——一种数据格式,可以用于描述应用级别的API语义。

参考资料:

  1. ALPS主页
  2. Spring Data Rest + Spring Secuirty
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015.12.07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实践
  • 分析
  • 参考资料:
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档