0

我将以下属性设置为 true "spring.hateoas.use-hal-as-default-json-media-type' 并添加 org.springframework.boot:spring-boot-starter-hateoas 作为依赖项。

代码

@Bean
public IntegrationFlow myUserFlow() {
    return IntegrationFlows
            .from(Http.inboundGateway("/user")
                    .requestMapping(r -> r.methods(HttpMethod.GET))
                    .get()
            )
            .handle((payload, headers) -> new MyUser("Joe Blogs")
                    .add(Link.of("http://localhost:8080/account", LinkRelation.of("account"))))
            .get();
}

回复

GET http://localhost:8080/user
HTTP/1.1 200 
connection: Keep-Alive, keep-alive
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 11 Jan 2021 18:31:13 GMT
Keep-Alive: timeout=60

{
  "name": "Joe Blogs",
  "links": [
    {
      "rel": "account",
      "href": "http://localhost:8080/account"
    }
  ]
}

Response code: 200; Time: 19ms; Content length: 87 bytes

我希望以 HAL 格式返回响应,例如

{
  "name": "Joe Blogs",
  "_links": [
    {
      "account":{
          "href": "http://localhost:8080/account"
       }
    }
  ]
}

为什么不是这样?我怎样才能做到这一点?

示例应用程序:https ://github.com/kevvvvyp/si-hateoas-demo

4

1 回答 1

1

解决方案是这样的:

public IntegrationFlow myUserFlow(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
    return IntegrationFlows
            .from(Http.inboundGateway("/user")
                    .messageConverters(requestMappingHandlerAdapter.getMessageConverters().toArray(HttpMessageConverter[]::new))

问题是因为 Spring Boot 没有自动配置 Spring Integration HTTP 通道适配器,它们肯定不知道您的 HAL 自定义。

因此,我们需要等到RequestMappingHandlerAdapterSpring Boot 和 hatoas 自定义处理。然后我们将它的转换器注入到我们的Http.inboundGateway().

我想说我们可能会在 Spring Boot 中考虑一些自动的东西来进行自定义,但是因为我们真的不谈论像 MVC 这样的基础设施,而是谈论@RequestMapping一些具体的 bean,所以坚持显式配置确实可能更好.

我不确定为什么我们不能使用HttpMessageConverters,但看起来RequestMappingHandlerAdapter是稍后配置的,当这种 bean ( IntegrtionFlow) 已经解析和创建时。

于 2021-01-11T20:17:28.113 回答