使用 spring hatoas 在集合实体上公开链接 [英] Exposing link on collection entity using spring hateoas

查看:34
本文介绍了使用 spring hatoas 在集合实体上公开链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题和这里问的差不多(在 spring 数据 REST 中公开集合实体的链接).但该主题中没有任何内容可以帮助我将自定义链接添加到集合调用.

I have pretty the same question as it has been asked here (Exposing link on collection entity in spring data REST). But nothing from that topic helps me to add custom link to collection call.

@Component
public class EventListResourceProcessor implements ResourceProcessor<Resources<Event>> {

    @Autowired
    private RepositoryEntityLinks entityLinks;

    @Override
    public Resources<Event> process(Resources<Event> events) {
        events.add(entityLinks.linkToCollectionResource(Event.class).withRel("events"));
        return events;
    }
}

在这种情况下永远不会调用 process 方法.

process method is never called in this case.

我需要调用 http://localhost:8080/event 并在 my_custom_link 下获取以下 JSON_链接部分:

I need to call http://localhost:8080/event and get the following JSON with my_custom_link under _links section:

{
  "_embedded": {
    "event": [
      {
        "id": "1",
        "name": "Updated event"
      }]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/event"
    },
    "profile": {
      "href": "http://localhost:8080/profile/event"
    },
    "my_custom_link": {
      "href": "http://localhost:8080/custom/"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 4,
    "totalPages": 1,
    "number": 0
  }
}

}

你能给我建议吗?

提前致谢!

推荐答案

因为我遇到了同样的问题,我希望在这里得到答案.解决方案是声明一个 bean ResourceProcessor 实现正确的泛型类型,它扩展了 ResourceSupport.

Because I faced the same issue and I hoped an answer here. The solution is to declare a bean ResourceProcessor implementing the right generic type which extends ResourceSupport.

在我们的可分页资源的例子中,正确的 ResourceSupportPagedResources> 作为以下示例:

In our case for a paginable resource, the right ResourceSupport is PagedResources<Resource<MyInterface>> as the following sample :

@Bean
public ResourceProcessor<PagedResources<Resource<Supplier>>> pageableSupplierProcessor() {
    return new ResourceProcessor<PagedResources<Resource<Supplier>>>() {
        @Override
        public PagedResources<Resource<Supplier>> process(PagedResources<Resource<Supplier>> resources) {
            Method registerMethod;
            try {
                registerMethod = SupplierRegistrationController.class.getMethod("register",
                        RegistrationRequest.class);
                Link registerLink = linkTo(registerMethod, new RegistrationRequest()).withRel("register");
                resources.add(registerLink);
                return resources;
            } catch (NoSuchMethodException | SecurityException e) {
                throw new IllegalStateException(e);
            }
        }
    };
}

这篇关于使用 spring hatoas 在集合实体上公开链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆