2

到目前为止,我从各种文件和 tuts 中获得并学到了以下几点:

  1. Spring Data Rest (SDR) 用于将我们的 Spring Data Repository 公开为 REST 服务,以便人们可以使用它进行自我探索,而无需手动创建 JAXRS。它仅适用于 Repository 层,除了使用RepositoryRestMvcConfiguration. 它在内部某处使用 Spring HATEOAS。

  2. Spring HATEOAS 用于在我们通过 Controller 或 REST 端点返回的实体中创建链接。我们必须ResourceSupport扩展我们的实体或Resource包装类来包装我们的实体以创建或添加链接。有几个注解和类可以使用,例如@EnableHyperediaSupportEntityLinks

可能有些点我还没有探索或了解,但我只是好奇我们如何将 SDR 结合到 HATEOAS 链接构建过程中?比如说。

EntityBean bean = repository.findByName(name);
Resource<EntityBean> resource = new Resource<EntityBean>(bean);
//JaxRsLinkBuilder.linkTo(TestResource.class).withRel("entity")     // this also works   
//ControllerLinkBuilder.linkTo(TestResource.class).withRel("myRel") // this also works
// I am curious how ControllerLinkBuilder and JaxRSLinkBuilder both are working for JaxRS.  
//Here TestResource is my REST service class. now in below line: 
resource.add(JaxRsLinkBuilder.linkTo(MyRepository.class).withRel("sdf")); //not working
// MyRepository is SDR exposed repository, which I thought should work but not working.
return resource;  

所以,我只是想将我暴露的REST存储库包含到手动 HATEOAS 链接构建过程中.. 可以这样做吗?

4

1 回答 1

3

您应该能够使用Spring-HATEOAS ResourceProcessor来构建链接。

例子:

@Component
public class MyBeanResourceProcessor implements ResourceProcessor<Resource<MyBean>> {

    @Autowired
    private EntityLinks entityLinks;

    public Resource<MyBean> process(Resource<MyBean> resource) {
        MyBean mybean = resource.getContent();

        // Do your linking here using entity class
        //EntityBean bean = repository.findByName(name);
        //Resource<EntityBean> resource = new Resource<EntityBean>(bean);
        // assuming you are linking to a single resource and bean.getId() method... check entitylinks for other methods
        //resource.add(entityLinks.linkForSingleResource(bean.class,bean.getId()).withRel("sdf"));

        return resource;
    }

}
于 2014-05-21T14:34:15.700 回答