【问题标题】:Remove Spring data rest self link templating in projections删除预测中的 Spring 数据休息自链接模板
【发布时间】:2018-09-15 17:08:01
【问题描述】:
{
  "_embedded" : {
    "patient" : {
      "firstName" : "Kidus",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8090/api/patients/2{?projection}",
          "templated" : true
        },
    }
}

如您所见,我有一个嵌入式实体(患者)。它返回所有数据,包括指向实体的链接,但链接是模板化的。我没有使用前端 HATEOAS 客户端,我也不打算改变这方面的路线。所以我需要一个普通的非模板链接。有没有什么简单的方法来实现这一点?

【问题讨论】:

  • 如果您使用 Spring HATEOAS 并在资源类上定义投影,则 self 链接将被模板化。这是 Spring 强制执行的约定,因此没有“非 hacky”方式来改变它(但可能有一种 hacky 方式)。

标签: spring-boot spring-data spring-data-jpa spring-data-rest


【解决方案1】:

您可以通过这种方式强制扩展模板:

@GetMapping("/myresources/{id}")
public EntityModel<MyResource> myResource(String id) {

    MyResource resource = ...;
    return new EntityModel<>(
                  resource,
                  linkTo(methodOn(getClass()).myResource(id)).withSelfRel().expand(id));
}

【讨论】:

    【解决方案2】:

    您可以使用自定义RepresentationModelProcessor 修改self 链接:

    @Component
    public class MyProjectionProcessor implements RepresentationModelProcessor<EntityModel<MyProjection>> {
    
        private static final Pattern TEMPLATE_PATTERN = Pattern.compile("\\{\\?.*");
    
        @Override
        public EntityModel<MyProjection> process(final EntityModel<MyProjection> model) {
            // copy the model without links
            final EntityModel<MyProjection> newModel = EntityModel.of(model.getContent());
            // loop over links
            for (final Link link : model.getLinks()) {
                Link newLink = link;
                // replace self link if it is templated
                if (link.hasRel(IanaLinkRelations.SELF) && link.isTemplated()) {
                    final String href = TEMPLATE_PATTERN.matcher(link.getHref()).replaceFirst("");
                    newLink = Link.of(href, IanaLinkRelations.SELF);
                }
                newModel.add(newLink);
            }
            return newModel;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多