【问题标题】:Spring Data Rest integration with Spring HATEOASSpring Data Rest 与 Spring HATEOAS 的集成
【发布时间】:2014-07-05 00:58:18
【问题描述】:

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

  1. Spring Data Rest (SDR) 用于将我们的 Spring Data Repository 公开为 REST 服务,以便人们可以使用它进行自我探索,而无需手动创建 JAXRS。它仅适用于 Repository 层,除了使用RepositoryRestMvcConfiguration 的配置之外,我们无法控制其工作方式的修改或添加。它在内部某处使用 Spring HATEOAS。

  2. Spring HATEOAS 用于在我们通过控制器或 REST 端点返回的实体内创建链接。我们得到ResourceSupport 来扩展我们的实体或Resource 包装类来包装我们的实体以创建或添加链接。有几个注解和类可供使用,例如 @EnableHyperediaSupport 和 EntityLinks。

可能有一些我还没有探索或了解的点,但我只是好奇我们如何将 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 链接构建过程中.. 可以这样做吗?

【问题讨论】:

    标签: spring spring-data-rest spring-hateoas


    【解决方案1】:

    您应该能够使用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;
        }
    
    }
    

    【讨论】:

    • 澄清这里的解决方案是正确的。你想做与你所要求的相反的事情。那就是你没有将 spring-data-rest 包含在 hatos 中,而是 spring-data-rest 已经包含了 hatos。所以使用 spring-data-rest 然后定义一个自定义的 hatos 资源处理器,spring-data-rest 将使用它。
    猜你喜欢
    • 2013-10-31
    • 2014-03-07
    • 2014-08-16
    • 2018-07-23
    • 2016-05-23
    • 2013-12-07
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多