集册 Spring Boot 入门实践 Spring Boot: Data Rest Service

Spring Boot: Data Rest Service

欢马劈雪     最近更新时间:2020-08-04 05:37:59

752

在文章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信息

分析

展开阅读全文