【问题标题】:How to add custom links to non repository rest controller in spring data rest hal?如何在spring data rest hal中添加自定义链接到非存储库rest控制器?
【发布时间】:2017-08-15 19:31:54
【问题描述】:

我想添加自定义的 rest 控制器以添加到入口点的 json/hal 响应中,以及 spring 添加的所有存储库。我正在通过两个问题来解决这个问题:

  1. 如何添加自定义控制器,使其与存储库的链接一起显示在入口点上?

  2. 如何在存储库生成的实体表示上添加指向我的自定义控制器的链接,以便我可以链接到我的自定义控制器?

我挣扎了一段时间,使用 spring-data-mongodb 创建了一个github project 来说明我的意思。有一个简单的实体 InvoiceInvoiceRepository,它扩展了 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"
    }
  }
}

【问题讨论】:

标签: spring-data-mongodb spring-data-rest spring-hateoas


【解决方案1】:

正如 Alan 所说,StackOverflow 上已经给出了答案:

  1. Q1

  2. Q2

对于其他读者,我已经用两个 UseCases 的示例实现更新了我的 Github 项目。享受spring-data-rest-hal-custom

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-06
    • 2015-12-31
    • 2015-05-30
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2017-11-29
    相关资源
    最近更新 更多