发布于 2016-01-21 06:56:11 | 248 次阅读 | 评论: 0 | 来源: 分享

这里有新鲜出炉的精品教程,程序狗速度看过来!

Spring Boot

Spring Boot 项目旨在简化创建产品级的 Spring 应用和服务。你可通过它来选择不同的 Spring 平台。可创建独立的 Java 应用和 Web 应用,同时提供了命令行工具来允许 'spring scripts'.


在文章 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语义。

参考资料:

  1. ALPS主页
  2. Spring Data Rest + Spring Secuirty


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务