在文章RESTful by Spring Boot with MySQL通過在Controller中引入BookRepository來對(duì)外提供REST API。Spring Boot還可以通過spring-boot-starter-data-rest
來對(duì)外提供REST API,可以免于編寫對(duì)應(yīng)的Controller,且具備分頁和排序的功能。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
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> {
}
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
,將會(huì)得到如下結(jié)果
http://wiki.jikexueyuan.com/project/spring-boot-cookbook-zh/images/54.png" alt="訪問author信息" />顯然,通過繼承PagingAndSortingRepository接口,比直接寫Controller能提供更多的功能:分頁查詢和對(duì)查詢結(jié)果排序。
@RepositoryRestResource注解讓編程人員可以直接通過repository提供數(shù)據(jù)接口,在這個(gè)“前端負(fù)責(zé)V和C,后端負(fù)責(zé)提供數(shù)據(jù)”的時(shí)代,非常方便;并且,可以通過給該注解傳入?yún)?shù)來改變URL。
只要在項(xiàng)目的classpath中包含spring-boot-starter-data-rest,同時(shí)就包含了spring-hateoas庫支持,這個(gè)庫可以提供ALPS元數(shù)據(jù)——一種數(shù)據(jù)格式,可以用于描述應(yīng)用級(jí)別的API語義。