首页 > 解决方案 > Spring Data Rest - 自定义端点名称

问题描述

默认情况下,Spring 数据 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

甚至不同的方法名称

谢谢

标签: springspring-bootspring-data-rest

解决方案


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

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

  • URL 路径的路径
  • rel为链接 ID

通过执行 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/"
    }
  }
}

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


推荐阅读