使用 RestTemplate 使用基于 HAL 的 API 时自动填充 _link-ed 成员对象

Auto-populate _link-ed member objects when consuming HAL based APIs with RestTemplate

使用 Spring RestTemplate,我想使用像这样的简化配置的基于 HAL 的 REST 服务:

GET http://my.rest.service/items/123 returns

{
    "_links": {
        "category": {
            "href": "/categories/321"
        },
        "self": {
            "href": "/items/123"
        }
    },
    "name": "my wonderful item"
}

http://my.rest.service/categories/321 上的 GET 将相应地 return 我的项目分配到的类别(看起来与上面的 JSON 非常相似)。

到目前为止我能做的(以及正在工作的 :))是一些 "manual" link-以下:

public Item getItemById(Integer itemId) {
    RestTemplate restTemplate = getRestTemplateWithHalMessageConverter();

    ResponseEntity<Resource<Budget>> response =
        restTemplate.exchange("http://my.rest.service/items/"+itemId,
            HttpMethod.GET, getHttpEntity(), 
            new ParameterizedTypeReference<Resource<Item>>() {}
        );

    ResponseEntity<Resource<Category>> catResponse =
        restTemplate.exchange("http://my.rest.service/" + 
            response.getBody().getLink("category").getHref(),
            HttpMethod.GET, getHttpEntity(), 
            new ParameterizedTypeReference<Resource<Category>>() {}
        );

    Item result = response.getBody().getContent();
    //^^ Now this is an item with NULL in category field

    result.setCategory(catResponse.getBody().getContent());
    //And voila, now the category is assigned

    return result;
}

(我没有 post "helper" 像 getRestTemplateWithHalMessageConverter() 这样的功能,恕我直言,它们与这个问题无关,尤其是当它们按预期工作时。)

我想要实现的是 "auto-following" HAL 响应中的 link 并分别填充我的 Java 对象。

所以,我的问题是,有没有什么方法可以让 "automatic" _link 跟随,这样我的 Item 将在没有第二个 exchange 等的情况下完全填充.?这是一个简单的例子,但我有很多 link 的更复杂的对象。当然,可以假设匹配字段存在于特定的 类.

关于奖励问题 ;) : 这可以与某种缓存一起使用吗?如果我有 30 个类别为 8 的项目,我不希望对 category 端点进行 30 次调用...

如果这两个问题都没有开箱即用的解决方案(至少我没有找到...),我将不得不自己写一个,我没意见!只是想确保我不会因为错过了什么而重新发明轮子...

非常感谢!!

您可以使用 Bowman to consume JSON+HAL resources in JAVA. This library greatly simplifies the consumption of resources comparing to RestTemplate as shown in this article

这个库回答了 "automatic link following" 部分:

Our client is a wrapper around Spring HATEOAS and Jackson with a heavy JPA influence. Retrieving an object from the remote returns a proxy of the returned object, instrumented using Javassist, whose accessors can transparently conduct further remote service invocations in accordance with its HAL links. This allows linked and inline associations to both be defined in the same way in the client model and greatly simplifies client code.

一段时间后,我完成了我自己对原始问题的解决方案(在 baxbong 友善地指出 Bowman 之前开始)。

如果有其他人与我有完全相同的需求,您可以在这里找到我的实现:

https://github.com/ahuemmer/storesthal

如那里所述,我将继续扩展它,因为有一些需求(由我或其他人)。 :) 当然,每个人都可以自由提出问题或拉取请求!