Spring Data REST 入門

REST,Spring Data
Remote
1
03:32 PM · Dec 01 ,2025

1. 概述

本文將解釋 Spring Data REST 的基本原理,並演示如何使用它來構建一個簡單的 REST API。

通常,Spring Data REST 構建在 Spring Data 項目之上,並使構建基於超媒體的 REST Web 服務變得容易,這些服務連接到 Spring Data 存儲庫——所有這些都使用 HAL 作為驅動超媒體類型的。

它消除了與這些任務相關的通常手動工作,並使 Web 應用程序的基本 CRUD 功能實現變得非常簡單。

2. Maven 依賴項

以下 Maven 依賴項對於我們的簡單應用程序是必需的:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId
    <artifactId>spring-boot-starter-data-rest</artifactId></dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

我們決定使用 Spring Boot 作為這個示例,但經典的 Spring 也可以正常工作。我們還選擇使用嵌入式 H2 數據庫,以避免額外的設置,但這個示例可以應用於任何數據庫。

3. 編寫應用程序

我們首先將編寫一個領域對象來表示我們網站中的用户:

@Entity
public class WebsiteUser {

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

    private String name;
    private String email;

    // standard getters and setters
}

每個用户都有一個姓名和電子郵件,以及自動生成的id。現在我們可以編寫一個簡單的存儲庫:

@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 主類來初始化應用程序:

@SpringBootApplication
public class SpringDataRestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringDataRestApplication.class, args);
    }
}

這就完成了!我們現在擁有一個完全功能齊全的 REST API。讓我們看看它在行動中。

4. 訪問 REST API

如果運行應用程序並前往 http://localhost:8080/ 在瀏覽器中,我們將收到以下 JSON:

{
  "_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 添加一個用户。

$ curl -i -X POST -H "Content-Type:application/json" -d '{  "name" : "Test", \ 
"email" : "[email protected]" }' http://localhost:8080/users
{
  "name" : "test",
  "email" : "[email protected]",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/1"
    },
    "websiteUser" : {
      "href" : "http://localhost:8080/users/1"
    }
  }
}

讓我們來查看響應頭信息:

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 訪問此用户。

{
  "name" : "test",
  "email" : "[email protected]",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/1"
    },
    "websiteUser" : {
      "href" : "http://localhost:8080/users/1"
    }
  }
}
{
  "_embedded" : {
    "users" : [ {
      "name" : "test",
      "email" : "[email protected]",
      "_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 的基本知識。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.