spring - 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
甚至不同的方法名称
- 改变
find_by_username
:http://localhost:8080/users/search/by_username?username=test
- (剥离
find_by_username
):http://localhost:8080/users/search?username=test
谢谢
解决方案
该@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/"
}
}
}
有关更多详细信息,您可以查看她
推荐阅读
- python - 问:Selenium NoSuchElementException(非显式等待或 iframe)
- user-interface - 如何在 Julia、WebIO 和 Blink 中使用 handle(w, “flag”)?
- c# - C# Entity Framework LINQ to Entities 在 SELECT 表达式下添加参数 WHERE 表达式
- python - 我不明白 django 的 path() 是如何工作的
- vue.js - 如何访问 vue.js 中的索引以获取循环元素?
- unity3d - Unity 2D Top-Down 鼠标面临武器旋转问题
- android - 在没有 xml 的情况下以编程方式创建 Listview:不显示任何单元格
- python - 如何在 output.csv 文件中包含“for”循环变量
- python - 超过指定数量。的列用 Pandas 重命名
- angular - Angular:在产品模式下点击刷新后 URL 发生变化