如何让Spring Integration Http.inboundGateway返回HAL Json



我将以下属性设置为true"spring.hateoas.使用hal作为默认的json媒体类型'&添加了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

解决方案如下:

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

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

因此,我们需要等到SpringBoot和hateoas自定义处理了RequestMappingHandlerAdapter。然后我们取它的转换器并将它们注入到我们的Http.inboundGateway()中。

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

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

最新更新