【问题标题】:How to get Spring Integration Http.inboundGateway to return HAL Json?如何让 Spring Integration Http.inboundGateway 返回 HAL Json?
【发布时间】:2021-01-11 18:34:53
【问题描述】:

我将以下属性设置为 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

【问题讨论】:

    标签: spring-integration spring-hateoas spring-integration-http


    【解决方案1】:

    解决办法是这样的:

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

    问题在于 Spring Integration HTTP 通道适配器不是 Spring Boot 自动配置的,而且它们肯定不知道您的 HAL 自定义。

    所以,我们需要等到RequestMappingHandlerAdapter 被Spring Boot 和hateoas 自定义处理。然后我们将它的转换器注入到我们的Http.inboundGateway()

    我想说的是,我们可能会考虑在 Spring Boot 中自动执行一些自定义功能,但是由于我们真的不谈论像 MVC 的 @RequestMapping 这样的一些基础架构,而是谈论一些具体的 bean,它真的可能更好坚持使用显式配置。

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

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2015-08-27
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多