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

How do I export data in accordance to HAL spec?

根据 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 ... */
}

正如我们所见,它在 "links" 字段中导出链接,没有前导下划线。是否需要额外配置才能根据 HAL 规范导出数据?

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

@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)

查看类似问题here and the docs

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

spring.hateoas.use-hal-as-default-json-media-type: true

经过深思熟虑,我发现了这个片段。

  @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 来处理俄语字符串。