在 Spring 集成 Java DSL 中设置响应 Http:InboundGateway StatusCode

Set Response Http:InboundGateway StatusCode in Spring Integration Java DSL

配置的以下位接受一个 HTTP POST 和一个要创建的用户实例的 JSON 请求主体,但如果我能得到它我就很危险 return一个201 Created。有什么想法吗?

@Bean
public IntegrationFlow flow(UserService userService) {
    return IntegrationFlows.from(
            Http.inboundGateway("/users")
            .requestMapping(r -> r.methods(HttpMethod.POST))
            .statusCodeFunction(f -> HttpStatus.CREATED)
            .requestPayloadType(User.class)
            .replyChannel(replyChannel())
            .requestChannel(inputChannel())
        )
        .handle((p, h) -> userService.create((User) p)).get();
}

我试过在 HttpRequestHandlerEndpointSpec 上调用 statusCodeFunction,但我一定是做错了。

答案是 statusCodeFunction 只适用于入站适配器(即单向进入的东西)。有点回避为什么我可以在 网关 上调用它的问题,但是哼哼...

IntegrationFlow 上使用 enrichHeaders 成功了。

@Configuration
@EnableIntegration
@Profile("integration")
public class IntegrationConfiguration {
    @Autowired
    UserService userService;

    @Bean
    public DirectChannel inputChannel() {
        return new DirectChannel();
    }

    @Bean
    public DirectChannel replyChannel() {
        return new DirectChannel();
    }

    @Bean
    public HttpRequestHandlingMessagingGateway httpGate() {
        HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true);
        RequestMapping requestMapping = new RequestMapping();
        requestMapping.setMethods(HttpMethod.POST);
        requestMapping.setPathPatterns("/users");
        gateway.setRequestPayloadType(User.class);
        gateway.setRequestMapping(requestMapping);
        gateway.setRequestChannel(inputChannel());
        gateway.setReplyChannel(replyChannel());
        return gateway;
    }

    @Bean
    public IntegrationFlow flow(UserService userService) {
        return IntegrationFlows.from(httpGate()).handle((p, h) -> userService.create((User) p))
                .enrichHeaders(
                        c -> c.header(org.springframework.integration.http.HttpHeaders.STATUS_CODE, HttpStatus.CREATED))
                .get();
    }
}