Spring Data REST简介

Introduction to Spring Data REST

1.概述

本文将解释Spring Data REST的基础知识,并展示如何使用它来构建简单的REST API。

通常,Spring Data REST是在Spring Data项目的基础上构建的,可轻松构建连接到Spring Data存储库的超媒体驱动的REST Web服务-所有这些都使用HAL作为驱动超媒体类型。

它消除了通常与此类任务相关的许多手动工作,并使Web应用程序的基本CRUD功能的实现非常简单。

2. Maven依赖

以下Maven依赖项是我们简单应用程序所必需的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
    <groupId>org.springframework.boot</groupId>
    spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId
    spring-boot-starter-data-rest</artifactId></dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    h2</artifactId>
</dependency>

我们决定在这个示例中使用Spring Boot,但是经典的Spring也可以正常工作。我们还选择使用H2嵌入式数据库以避免任何额外的设置,但是该示例可以应用于任何数据库。

3.编写应用程序

我们将首先编写一个表示我们网站用户的域对象:

1
2
3
4
5
6
7
8
9
10
11
12
@Entity
public class WebsiteUser {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;
    private String email;

    // standard getters and setters
}

每个用户都有一个名称和一封电子邮件,以及一个自动生成的ID。现在我们可以编写一个简单的存储库:

1
2
3
4
@RepositoryRestResource(collectionResourceRel ="users", path ="users")
public interface UserRepository extends PagingAndSortingRepository<WebsiteUser, Long> {
    List<WebsiteUser> findByName(@Param("name") String name);
}

该界面允许您对WebsiteUser对象执行各种操作。我们还定义了一个自定义查询,该查询将基于给定名称提供用户列表。

@RepositoryRestResource批注是可选的,用于自定义REST端点。如果我们决定省略它,Spring将自动在" / websiteUsers"而不是" / users"处创建一个端点。

最后,我们将编写一个标准的Spring Boot主类来初始化应用程序:

1
2
3
4
5
6
@SpringBootApplication
public class SpringDataRestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringDataRestApplication.class, args);
    }
}

而已!现在,我们有了功能齐全的REST API。让我们来看看它的实际作用。

4.访问REST API

如果我们运行该应用程序并在浏览器中转到http:// localhost:8080 /,我们将收到以下JSON:

1
2
3
4
5
6
7
8
9
10
11
{
 "_links" : {
   "users" : {
     "href" :"http://localhost:8080/users{?page,size,sort}",
     "templated" : true
    },
   "profile" : {
     "href" :"http://localhost:8080/profile"
    }
  }
}

如您所见,有一个" / users"端点可用,它已经具有"?page","?size"和"?sort"选项。

还有一个标准的" / profile"端点,它提供应用程序元数据。重要的是要注意,响应的结构遵循REST体系结构样式的约束。具体来说,它提供了统一的界面和自描述消息。这意味着每个消息都包含足够的信息来描述如何处理该消息。

我们的应用程序中尚无用户,因此转到http:// localhost:8080 / users只会显示一个空用户列表。让我们使用curl来添加用户。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ curl -i -X POST -H"Content-Type:application/json" -d '{ "name" :"Test", \
"email" :"[emailprotected]" }'
http://localhost:8080/users
{
 "name" :"test",
 "email" :"[emailprotected]",
 "_links" : {
   "self" : {
     "href" :"http://localhost:8080/users/1"
    },
   "websiteUser" : {
     "href" :"http://localhost:8080/users/1"
    }
  }
}

让我们来看看响应头:

1
2
3
4
5
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/users/1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked

您会注意到返回的内容类型为" application / hal + json"。 HAL是一种简单的格式,它提供了一种一致且简单的方法来在API中的资源之间建立超链接。标头还自动包含Location标头,这是我们可以用来访问新创建的用户的地址。

我们现在可以通过http:// localhost:8080 / users / 1访问该用户

1
2
3
4
5
6
7
8
9
10
11
12
{
 "name" :"test",
 "email" :"[emailprotected]",
 "_links" : {
   "self" : {
     "href" :"http://localhost:8080/users/1"
    },
   "websiteUser" : {
     "href" :"http://localhost:8080/users/1"
    }
  }
}

您还可以使用curl或任何其他REST客户端来发出PUT,PATCH和DELETE请求。还需要注意的是,Spring Data REST自动遵循HATEOAS的原理。 HATEOAS是REST体系结构样式的约束之一,这意味着应使用超文本来查找通过API的方法。

最后,让我们尝试访问我们之前编写的自定义查询,并找到所有名称为" test"的用户。这是通过转到http:// localhost:8080 / users / search / findByName?name = test来完成的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
 "_embedded" : {
   "users" : [ {
     "name" :"test",
     "email" :"[emailprotected]",
     "_links" : {
       "self" : {
         "href" :"http://localhost:8080/users/1"
        },
       "websiteUser" : {
         "href" :"http://localhost:8080/users/1"
        }
      }
    } ]
  },
 "_links" : {
   "self" : {
     "href" :"http://localhost:8080/users/search/findByName?name=test"
    }
  }
}

5.结论

本教程演示了使用Spring Data REST创建简单的REST API的基础。可以在链接的GitHub项目中找到本文中使用的示例。