You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Cloud Gateway MVC修改请求体时遇空指针异常求助

问题解决:Spring Cloud Gateway MVC 修改请求体时触发 NullPointerException

问题根因

你遇到的空指针异常,是因为modifyRequestBody这类网关过滤器依赖Spring Cloud Gateway MVC的属性上下文,但直接用http()做转发时,并未初始化该上下文,导致MvcUtils.getGatewayAttributes()返回null,进而触发Map.put操作的空指针。

修复方案

需要用GatewayMvcFunctions.gateway()包装转发目标,初始化网关所需的属性上下文,再添加modifyRequestBody过滤器。

修改后的完整代码:

import org.springframework.cloud.gateway.server.mvc.GatewayMvcFunctions;
// 其他必要导入...

@Bean
RouterFunction<ServerResponse> testRoute(){
    return route()
            .route(path("/test").and(method(HttpMethod.POST)), 
                   GatewayMvcFunctions.gateway(http("http://httpbin.org")))
            .before(setPath("/post"))
            .before(modifyRequestBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE, (serverRequest, s) -> {
                LOGGER.info(s);
                return s;
            }))
            .build();
}

关键说明

  • GatewayMvcFunctions.gateway()会为请求初始化网关属性Map,确保modifyRequestBody等网关专属过滤器能正常访问上下文数据。
  • 原代码直接使用http()属于普通WebClient转发,不具备网关过滤器的上下文支持,因此无法兼容modifyRequestBody这类依赖网关上下文的操作。

内容的提问来源于stack exchange,提问作者bsgrd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:52:15