Spring Gateway修改RequestBody启动报错及代码求助
问题分析与解决方案
核心问题
启动报错The elements [spring.cloud.gateway.routes[0].filters[0].modifyrequestbody.class] were left unbound的原因是:
- 你混淆了内置ModifyRequestBody过滤器和自定义GatewayFilter的配置方式:内置ModifyRequestBody的配置参数中不存在
class字段,却在YAML里强行添加,导致Spring无法解析配置。 - 自定义Filter代码存在语法错误,同时逻辑处理不当。
解决方案(两种可选)
方案一:修复自定义Filter并正确配置
1. 修正自定义Filter代码
@Slf4j public class SomeFilter implements GatewayFilter { private final ModifyRequestBodyGatewayFilterFactory factory; // 构造函数名必须与类名一致,原代码写为RedirectionFilter是错误的 public SomeFilter(ModifyRequestBodyGatewayFilterFactory factory) { this.factory = factory; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ModifyRequestBodyGatewayFilterFactory.Config cfg = new ModifyRequestBodyGatewayFilterFactory.Config(); cfg.setContentType("application/json"); cfg.setRewriteFunction(String.class, String.class, new MyRewriteFunction()); // 必须返回ModifyRequestBody处理后的Mono,否则会重复执行过滤器链 return factory.apply(cfg).filter(exchange, chain); } }
2. 注册自定义Filter为Spring Bean
创建配置类将Filter注入Spring容器:
@Configuration public class GatewayConfig { @Bean public SomeFilter someFilter(ModifyRequestBodyGatewayFilterFactory factory) { return new SomeFilter(factory); } }
3. 修改YAML配置
移除错误的ModifyRequestBody配置块,直接引用自定义Filter的Bean名称:
routes: - id: order-route-1 uri: http://localhost:8999/ predicates: - Path=/some/path1 - Method=POST filters: - Name=someFilter # 对应@Bean方法名
方案二:直接使用内置ModifyRequestBody过滤器(更简洁)
无需自定义Filter,直接结合自定义RewriteFunction即可:
1. 修正并注册RewriteFunction为Bean
@Slf4j @Component // 直接注册为Bean public class MyRewriteFunction implements RewriteFunction<String, String> { @Override public Publisher<String> apply(ServerWebExchange exchange, String s) { try { ObjectMapper objectMapper = new ObjectMapper(); HelloObject obj = objectMapper.readValue(s, HelloObject.class); String newBody = objectMapper.writeValueAsString(obj.getData()); return Mono.just(newBody); } catch (Exception e) { log.error("Error while parsing body", e); } return Mono.just(s); } }
2. 修改YAML配置
直接使用内置ModifyRequestBody过滤器,指定RewriteFunction的Bean名称:
routes: - id: order-route-1 uri: http://localhost:8999/ predicates: - Path=/some/path1 - Method=POST filters: - ModifyRequestBody: contentType: application/json rewriteFunction: myRewriteFunction # 对应Bean名称(类名首字母小写)
额外代码修正
MyRewriteFunction原代码存在多余大括号,已在上述代码中修正;同时建议复用同一个ObjectMapper,避免重复创建对象浪费资源。
内容的提问来源于stack exchange,提问作者ha22109
相关产品推荐
相关产品推荐

