如何根据HAL规范导出数据?

时间:2018-01-22 03:46:20

标签: spring-data hateoas spring-hateoas

根据this规范,以hal + json格式公开数据的应用程序应在_links json字段中提供嵌入式链接。但是,如果我在spring-data 1.5.9中声明我的REST存储库,就像这样:

@RepositoryRestResource(path = "storage-node", excerptProjection = IBrief.class)
public interface IStorageNodeRepository extends JpaRepository<StorageNode, Long> {
  @Query("FROM StorageNode sn WHERE sn.parent is null order by sn.uploadTs ASC")
  List<StorageNode> findAllRootNodes();
}

我得到以下json:

{
  "nodeType" : "Image",
  "text" : "100.jpeg",
  "uploadTs" : "2018-01-11T23:48:25.724Z",
   /* ... Irrelevant ... */
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost:8080/emerald/api/hal/storage-node/31"
  }
  /* ... Irrelevant ... */
}

正如我们所看到的,它在“链接”字段中导出链接,没有前导下划线。是否需要其他配置才能根据HAL规范导出数据?

2 个答案:

答案 0 :(得分:1)

在考虑之后,我发现了这个片段。

  @Bean
  public RepositoryRestConfigurer repositoryRestConfigurer() {
    return new RepositoryRestConfigurerAdapter() {
      @Override
      public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.setBasePath("/api/hal");
        config.setDefaultMediaType(MediaType.APPLICATION_JSON_UTF8);
      }
    };
  }

删除默认媒体类型完成了这项工作。 我不记得我在哪些情况下添加了这个。也许我必须在每个回复中明确说出;charset=utf8来处理俄语字符串。

答案 1 :(得分:0)

我不相信Spring HATEOAS可以开箱即用。您可以通过在配置中添加以下内容来启用它:

@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)

查看类似问题heredocs

如果你正在使用spring boot,那么application.properties中的相关配置将是(尽管我相信在至少1.5.9的启动时默认为true):

spring.hateoas.use-hal-as-default-json-media-type: true
相关问题