【发布时间】:2017-08-15 19:31:54
【问题描述】:
我想添加自定义的 rest 控制器以添加到入口点的 json/hal 响应中,以及 spring 添加的所有存储库。我正在通过两个问题来解决这个问题:
如何添加自定义控制器,使其与存储库的链接一起显示在入口点上?
如何在存储库生成的实体表示上添加指向我的自定义控制器的链接,以便我可以链接到我的自定义控制器?
我挣扎了一段时间,使用 spring-data-mongodb 创建了一个github project 来说明我的意思。有一个简单的实体 Invoice 和 InvoiceRepository,它扩展了 MongoRepository 并具有一个特殊的查找方法 List<Invoice> findByFirstName(@Param("firstName")String firstName);。
此外,我希望将两个自定义控制器包含在服务入口点的_links 部分中-
使用Hal Browser,此刻的入口点是这样的
{
"_links": {
"invoices": {
"href": "http://localhost:8080/customize/invoices{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/customize/profile"
}
}
}
但我希望它是
"_links": {
"invoices": {
"href": "http://localhost:8080/customize/invoices{?page,size,sort}",
"templated": true
},
"export": {
"href": "http://localhost:8080/customize/export/invoices"
},
"custom":{
"href": "localhost:8080/customize/invoices/search/customList"
}
"profile": {
"href": "http://localhost:8080/customize/profile"
}
}
对于我问题的第二部分,我不知道如何实现。 发票的 JSON 表示形式如下所示:
{
"firstName": "Chuck",
"lastName": "Noris",
"amount": 2.5,
"exported": false,
"_links": {
"self": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
},
"invoice": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
}
}
}
我想通过自定义导出链接来扩展它到每个发票,像这样
{
"firstName": "Chuck",
"lastName": "Noris",
"amount": 2.5,
"exported": false,
"_links": {
"self": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
},
"invoice": {
"href": "http://localhost:8080/customize/invoices/27490450945023268364302849904"
}
"export": {
"href": "http://localhost:8080/customize/export/invoice/27490450945023268364302849904"
}
}
}
【问题讨论】:
-
@AlanHay 谢谢,我会试试的。抱歉,我自己没有在 stackoverflow 上找到这个。
标签: spring-data-mongodb spring-data-rest spring-hateoas