2

使用这行代码生成链接时:

indexResource.add(linkTo(IndexController.class).withSelfRel());

生成此 JSON:

{
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost:8080"
  } ]
}

但是,Spring Data Rest 生成的资源链接会生成以下 JSON:

{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons{?page,size,sort}",
      "templated" : true
    }
  }
}

特别是,我想模仿 Spring Data Rest 制作的那个。我该怎么做?

我正在使用具有以下配置的 Spring Boot:

@Configuration
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
@EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
@ComponentScan
public class Application { ... }

保留或删除@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)似乎并没有改变任何东西。

我还有以下 gradle 依赖项:

compile "org.springframework.boot:spring-boot-starter-data-rest"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-jetty"
compile "org.springframework.data:spring-data-envers:0.2.0.RELEASE"
compile "org.hibernate:hibernate-envers:4.3.6.Final"
runtime "mysql:mysql-connector-java:5.1.32"
testCompile "junit:junit"
4

4 回答 4

1

Spring Data Rest 使用 HAL 格式。它应该是较新版本的 Spring HATEOAS 的默认值。您可以使用 Configuration 类上的注释来激活它:

@EnableHypermediaSupport(type= {HypermediaType.HAL})

更新

我在使用 Spring Boot 时遇到了类似的情况。我必须将以下内容添加到我的 my 中pom.xml

<dependency>
  <groupId>org.springframework.plugin</groupId>
  <artifactId>spring-plugin-core</artifactId>
  <version>1.1.0.RELEASE</version>
</dependency>
于 2014-09-19T11:19:38.867 回答
1

为了生成 HAL 格式的 JSON,您的 HTTP 请求必须接受 application/hal+json(即 Accept 标头是 application/hal+json)。

您的应用程序的默认内容类型也可能是 application/json。您可以通过以下配置类将默认内容类型更改为 application/hal+json:

public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer c) {
        c.defaultContentType(MediaTypes.HAL_JSON);
    }
}
于 2015-07-02T15:55:18.600 回答
0

我建议创建两个类,如 Link 和 Self.Link 有 Self。自我有href和模板。创建一个将链接形成为 Java 对象的类。然后使用 Java 到 Json 库(如 GSON)获得与上述类似的输出

于 2014-09-19T04:51:21.660 回答
0

如果您使用以下请求标头发出请求

接受:应用程序/alps+json

你应该得到想要的结果,...

{
  “链接”:[{
    “rel”:“自我”,
    “href”:“http://localhost:8080”
  }]
}

如果您提出请求:

接受:应用程序/json

或者

接受:application/hal+json

然后你会得到 HAL(目前是默认的,见下面的链接)

{
  “_链接”:{
    “自己” : {
      "href" : "http://localhost:8080/persons{?page,size,sort}",
      “模板化”:真
    }
  }
}

https://github.com/spring-projects/spring-hateoas/blob/master/src/main/java/org/springframework/hateoas/config/EnableHypermediaSupport.java

于 2015-10-28T07:53:47.883 回答