Spring Data Rest - 自定义端点名称



默认情况下,Spring data REST 使用 camelCase 作为端点名称。

例如,如果存储库是

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Integer> {
    List<User> findByUsername(@Param("username") String username);
}

然后http://localhost:8080/users/search/findByUsername?username=test端点

如何自定义端点以使其使用snake_case,变得如下所示:http://localhost:8080/users/search/find_by_username?username=test

甚至不同的方法名称

  • 更改find_by_usernamehttp://localhost:8080/users/search/by_username?username=test
  • (剥离find_by_username):http://localhost:8080/users/search?username=test

谢谢

@RestResource注释还使我们能够自定义映射到存储库方法的 URL 路径以及 HATEOAS 资源发现返回的 JSON 中的链接 ID。

为此,我们使用注释的可选参数:

  • 网址路径的路径
  • 链接 ID 的 rel

通过执行 cUrl to http://localhost:8080/users/search/ ,我们现在可以看到我们的新方法与其他资源一起列出:

{
  "_links": {
    "findByUsername": {
      "href": "http://localhost:8080/users/search/findByUsername{?username}"
    },
    "self": {
      "href": "http://localhost:8080/users/search/"
    }
  }
}

因此,要自定义 rest url 端点,我们可以简单地添加 @RestResource 注释:

@RestResource(path = "byUsername", rel = "customFindMethod")
 List<User> findByUsername(@Param("username") String username);

如果我们再次执行资源发现,生成的 JSON 将确认我们的更改:

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

有关更多详细信息,您可以查看她

最新更新