在前面的例子中,我们使用BookResposity在REST控制器中,目的是通过RESTful API去暴露数据。然后,这样的声明是快捷的和容易的方式去调用数据,它要求我们创建控制器和声明映射的数据给请求操作。而这样的过程,Spring提供了相似的校报代码给我们使用,这个相似的应用就是在包spring-boot-starter-data-rest中。这个包中允许我们简单添加注释去响应接口,且Spring将会处理剩余的工作。

2.2.1代码实现

1.首先,我们在build.gradle中引入如下的包:

implementation 'org.springframework.boot:spring-boot-starter-data-rest'

2.现在,我们创建新的接口去声明AuthorRepository在src/main/java/org/owen/bookpub/repository包路径下。

 @RepositoryRestResource
public interface AuthorRepository extends
PagingAndSortingRepository<Author, Long> {
}

 

3.对于其它的model类,我们也这样创建,如下的代码。

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

 

@RepositoryRestResource
public interface ReviewerRepository extends
PagingAndSortingRepository<Reviewer, Long> {
}

 

4.最后,启动我们的项目,访问http://localhost:8080/authors,你将会看到如下的结果。

2.2创建Spring数据REST服务

2.2.2代码说明

从上面的代码中,我们已经看到了,我们只要继承PagingAndSortingRepository<T,TD>就可以实现上一节的功能。即PagingAndSortingRepository<T,ID>的功能就相当于我们先创建一个控制器,然后由控制器去调用我们创建的Repository,如BookRespository.

聪明的读者已经发现,我们在使用浏览器访问后获取的信息要比BookController来的多。这是因为BookController调用的BookRepository是继承了CrudRepository,但是AuthorRepository是继承了PagingAndSortingRepository,这个接口是CrudRepositoy接口的扩展。而使用PangAndSortRepository接口的目的是,我们可以获取额外的信息。

在我们操作的时候,@RepositoryRestResource注释可以让我们灵活去控制web端的数据暴露。例如,我们想要改变URL路或真实的值,我们要写writers替代authors,我们只需如下的写法:

 @RepositoryRestResource(collectionResourceRel = "writers",path = "writers")

public interface AuthorRepository extends

              PagingAndSortingRepository<Author, Long>

{

当我们引用spring-boot-starter-data-rest在我们依赖包中,我们将会引入spring-hateoas库,这个库提供了ALPS元数据,例如我们在访问页面看到的_links对象。这个对象非常有用,它有助于我们创建API驱动的UI,我们可以通过元数据信息导航我们要访问的路径。

相关文章:

  • 2021-05-14
  • 2021-11-26
  • 2021-06-07
  • 2022-01-09
  • 2022-02-01
  • 2021-08-20
  • 2022-12-23
猜你喜欢
  • 2021-08-02
  • 2022-02-07
  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2021-06-01
相关资源
相似解决方案