简体   繁体   English

如何通过Spring Hateoas中的注释设置资源关系?

[英]how to set resource relations through annotations in Spring Hateoas?

Is there a way to set resource relations through annotations? 有没有办法通过注释设置资源关系? I made a similar question a some time ago but i've not been clear enough. 我前段时间提过了类似的问题,但我还不够清楚。 I want to have something like this: 我想要这样的东西:

public class UserResource {

     private String username;

     @Relation(value = "{servicebaseUrl}/classes/${value}", rel = "class")
     private String classId;

     // Getters and setters
}

And then add a message converter which would add links only if client sends Accept = application/hal+json , avoiding the fact of doing two different controller endpoints for application/hal+json and application/json . 然后添加一个消息转换器,只有在客户端发送Accept = application/hal+json才会添加链接,从而避免为application/hal+jsonapplication/json执行两个不同的控制器端点。 Does Spring offers something like that? Spring会提供类似的东西吗? I found that it actually offers this @Relation annotation(or similar one) but it seems that it is not for the same purposes. 我发现它实际上提供了这个@Relation注释(或类似的注释),但似乎它不是出于同样的目的。

No this is not possible - you would have to implement a ResourceAssembler to add links to your resources. 不,这是不可能的 - 您必须实现ResourceAssembler以添加指向您资源的链接。

Usually your resources extend ResourceSupport . 通常,您的资源会扩展ResourceSupport

class PersonResource extends ResourceSupport {

  String firstname;
  String lastname;
}

Then your create ResourceAssembler to control the creation of that resource: 然后创建ResourceAssembler来控制该ResourceAssembler的创建:

class PersonResourceAssembler extends ResourceAssemblerSupport<Person, PersonResource> {

  public PersonResourceAssembler() {
    super(PersonController.class, PersonResource.class);
  }

  @Override
  public PersonResource toResource(Person person) {

    PersonResource resource = createResource(person);
    // … do further mapping and add links 
    resource.add(new Link("http://myhost/people"));
    return resource;
  }
}

See the spring hateoas documentation for details 有关详细信息,请参阅spring hateoas文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM