Spring Data RESTでのHTTPエンドポイントのカスタマイズ

Spring Data RESTでのHTTPエンドポイントのカスタマイズ

1. 前書き

Spring Data RESTは、RESTサービスに自然な多くの定型文を削除できます。

このチュートリアルでは、customize some of Spring Data REST’s HTTP binding defaultsを実行する方法について説明します。

2. Spring Data RESTリポジトリの基礎

開始するには、create an empty interface that extends the CrudRepository interfaceを使用して、エンティティのタイプとその主キーのタイプを指定します。

public interface UserRepository extends CrudRepository {}

デフォルトでは、Spring generates all the mappings neededは、適切なHTTPメソッドを介してアクセスできるように各リソースを構成し、適切なステータスコードを返します。

CrudRepositoryで定義されているすべてのリソースが必要ない場合は、基本的なRepositoryインターフェースとdefine only the resources we wantを拡張できます。

public interface UserRepository extends Repository {
  void deleteById(Long aLong);
}

リクエストを受信すると、存在する場合はSpring reads the HTTP Method used and, depending on the resource type, calls the appropriate method defined in our interface、それ以外の場合はHTTPステータス405 (Method Not Allowed)を返します。

上記のコードを参照すると、SpringはDELETEリクエストを受信すると、deleteByIdメソッドを実行します。

3. 公開されるHTTPメソッドの制限

ユーザー管理システムがあると想像してみましょう。 したがって、UserRepository.が発生する可能性があります

また、Spring Data RESTを使用しているため、CrudRepositoryを拡張することで多くのことが得られます。

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends CrudRepository {}

All our resources are exposed using the default CRUD patternなので、次のコマンドを発行します。

curl -v -X DELETE http://localhost:8080/users/

削除を確認するためにHTTPステータス204 (No Content returned)を返します。

ここで、内部で使用できる一方で、サードパーティからのwe want to hide the delete methodを想定しましょう。

次に、最初にdeleteByIdメソッドシグネチャをインターフェイスに追加できます。これにより、構成することをSpring DataRESTに通知します。

次に、アノテーション@RestResource(exported = false)を使用できます。これにより、configure Spring to skip this method when triggering the HTTP method exposureになります。

@Override
@RestResource(exported = false)
void deleteById(Long aLong);

ここで、上記と同じcUrlコマンドを繰り返すと、代わりにHTTPステータス405 (Method Not Allowed)を受け取ります。

4. サポートされているHTTPメソッドのカスタマイズ

@RestResourceアノテーションは、customize the URL path mapped to a repository methodと、HATEOASリソース検出によって返されるJSON内のリンクIDへの機能も提供します。

そのためには、注釈のオプションのパラメーターを使用します。

  • URLパスのpath

  • リンクIDのrel 

UserRepositoryに戻り、簡単なfindByEmailメソッドを追加しましょう。

WebsiteUser findByEmail(@Param("email") String email);

cUrlからhttp://localhost:8080/users/search/を実行すると、新しいメソッドが他のリソースとともに一覧表示されます。

{
  "_links": {
    "findByEmail": {
      "href": "http://localhost:8080/users/search/findByEmail{?email}"
    },
    "self": {
      "href": "http://localhost:8080/users/search/"
    }
  }
}

If we don’t like the default path, instead of changing the repository method, we can simply add the @RestResource annotation

@RestResource(path = "byEmail", rel = "customFindMethod")
WebsiteUser findByEmail(@Param("email") String email);

また、リソースの検出を再度実行すると、結果のJSONによって変更が確認されます。

{
  "_links": {
    "customFindMethod": {
      "href": "http://localhost:8080/users/search/byEmail{?email}",
      "templated": true
    },
    "self": {
      "href": "http://localhost:8080/users/search/"
    }
  }
}

5. プログラムによる構成

HTTPメソッドへのアクセスを公開または制限するために、より細かいレベルの構成が必要になる場合があります。 たとえば、コレクションリソースのPOST、およびアイテムリソースのPUTとPATCHは、すべて同じsaveメソッドを使用します。

Starting from Spring Data REST 3.1, and available with Spring Boot 2.1we can change the exposure of a specific HTTP methodからExposureConfiguration classまで。 この特定の構成クラスは、ラムダベースのAPIを公開して、グローバルルールとタイプベースのルールの両方を定義します。

たとえば、ExposureConfiguration を使用して、UserRepositoryに対するPATCH要求を制限できます。

public class RestConfig implements RepositoryRestConfigurer {
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration restConfig) {
        ExposureConfiguration config = restConfig.getExposureConfiguration();
        config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) ->
          httpMethods.disable(HttpMethod.PATCH));
    }
}

6. 結論

この記事では、リソースでデフォルトでサポートされているHTTPメソッドをカスタマイズするためにSpring Data RESTを構成する方法を検討しました。

いつものように、この記事で使用されている例は、GitHub projectにあります。