且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Spring HATEOAS更改HAL链接格式

更新时间:2023-02-15 15:45:09

为了使用HAL作为RESTful的消息格式语言 API,并启用自动分页,我们需要一些配置 我们的应用程序发生了变化.从Spring Data和Spring HATEOAS开始 已经提供了配置注释,我们需要添加 这些注释:

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
@EnableHypermediaSupport(type = { HypermediaType.HAL })
@ComponentScan(basePackages = {
        "com.jiwhiz.rest"
})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer c) {
        c.defaultContentType(MediaTypes.HAL_JSON);
    }
}

@EnableSpringDataWebSupport将添加对分页和 @EnableHypermediaSupport(type = {HypermediaType.HAL})将添加 超媒体支持.然后我们将默认内容类型设置为 application/hal + json.

引用:由Yuan Ji设计和构建带有Spring HATEOAS的RESTful API

I'm building a Spring REST application using Spring HATEOAS (0.16.0.RELEASE) and I'd like the JSON links output to look like:

_links: {
   self: {
     href: "https://<ip>/api/policies/321"
   }
}

while it renders like:

   "links":
      [{
       "rel":"self",
       "href":"http://<ip>/api/policies/321"
      }]

I'm using HATEOAS Resource and ResourceAssembler.

Why do I get this format instead of the other? How can I change it?

In order to use HAL as the message format language for our RESTful API, and enable automatic pagination, we need some configuration changes in our applicaiton. Since Spring Data and Spring HATEOAS already provides annotations for configuration, all we need is to add those annotations:

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
@EnableHypermediaSupport(type = { HypermediaType.HAL })
@ComponentScan(basePackages = {
        "com.jiwhiz.rest"
})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer c) {
        c.defaultContentType(MediaTypes.HAL_JSON);
    }
}

@EnableSpringDataWebSupport will add support for pagination and @EnableHypermediaSupport(type = { HypermediaType.HAL }) will add hypermedia support. Then we set default content type to application/hal+json.

cite: Design and Build RESTful API with Spring HATEOAS by Yuan Ji