Spring Boot 學習筆記(1.4):Data Rest Service
在文章 RESTful by Spring Boot with MySQL 通過在Controller中引入BookRepository來對外提供REST API。Spring Boot還可以通過 spring-boot-starter-data-rest 來對外提供REST API,可以免于編寫對應的Controller,且具備分頁和排序的功能。
實踐
- 在pom文件中添加依賴項
org.springframework.bootspring-boot-starter-data-rest
- 在包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 { }
- 可以看出,實際編寫的代碼很少,同樣套路,為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 { }
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 { }
- 啟動應用程序,并訪問 http://localhost:8080/authors ,將會得到如下結果
訪問author信息
分析
顯然,通過繼承PagingAndSortingRepository接口,比直接寫Controller能提供更多的功能:分頁查詢和對查詢結果排序。 @RepositoryRestResource注解讓編程人員可以直接通過repository提供數據接口,在這個“前端負責V和C,后端負責提供數據”的時代,非常方便;并且,可以通過給該注解傳入參數來改變URL。 只要在項目的classpath中包含spring-boot-starter-data-rest,同時就包含了spring-hateoas庫支持,這個庫可以提供 ALPS元數據 ——一種數據格式,可以用于描述應用級別的API語義。
參考資料:
本文由用戶 qrih2957 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!