根据反应内容在 Spring Weblux ServerResponse 上设置 header

Setting a header on a Spring Weblux ServerResponse based on reactive content

Spring 5 的 ServerResponse.HeadersBuilder provides a header(String, String) method to add a header to the response in a reactive stack (using the Functional Programming Model).

问题是我的 header 取决于我要检索的内容,例如:

public Mono<ServerResponse> getEntity(ServerRequest request) {
    String entityId = request.pathVariable("id");
    Mono<MyEntity> entity = service.findEntity(entityId);
    String headerValue = "???" // The header value depends on the values of the entity, which is not present at this point, here I only have access to the Mono 
    return ok().header("my-header", headerValue)
        .contentType(MediaType.APPLICATION_JSON)
        .body(entity , MyEntity.class);
  }

如何指定 'reactive' header?

通过映射您希望应用程序执行的操作

return service.findEntity(entityId).flatMap(entity -> {
    // Check entity and extract header the way you want

    return ok().header( ... );   
});