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

Spring Cloud Gateway自定义过滤器报错:找不到MyLogging GatewayFilterFactory

解决Spring Cloud Gateway自定义过滤器找不到的问题

这个错误Unable to find GatewayFilterFactory with name MyLogging本质是Spring容器没有正确注册你的自定义过滤器工厂类,导致Gateway无法识别它。下面是具体的排查和解决步骤:

1. 优先检查组件扫描范围

Spring Boot默认只会扫描主应用类所在包及其子包下的组件。如果你的MyLoggingGatewayFilterFactory类放在了主类扫描范围外的包中,Spring根本不会把它注册为Bean,Gateway自然找不到。

解决方法:

  • 最简单的方式:把过滤器类移动到主应用类所在的包(或其子包)下。比如主类在com.example.gateway,过滤器可以放在com.example.gateway.filters这样的子包中。
  • 如果不想移动代码,就在主应用类上添加@ComponentScan指定过滤器所在的包:
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.gateway", "com.your.filter.package"})
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

2. 确认过滤器类的注解与命名规则

  • 你的代码里已经给过滤器类加了@Component注解,这是正确的,但可以再检查是否有拼写错误(比如写成@Componet)。
  • 过滤器类命名必须以GatewayFilterFactory结尾,你的MyLoggingGatewayFilterFactory完全符合规则,Gateway会自动去掉后缀识别为MyLogging过滤器,所以配置里的name: MyLogging是正确的,不需要修改。

3. 检查YAML配置的缩进

YAML对缩进极其敏感,如果args的缩进层级错误,可能会导致配置解析异常,间接引发过滤器找不到的问题。确认你的配置缩进一致(比如统一用2个空格):

filters:
  - name: MyLogging
    args:
      baseMessage: My Custom Message
      preLogger: true
      postLogger: true

注意args要和name保持同一层级的缩进,不能错位。

4. 验证依赖兼容性

你使用的Spring Cloud Hoxton.SR8和Spring Boot 2.3.4.RELEASE是兼容的,但可以通过./gradlew dependencies命令查看依赖树,排查是否有依赖冲突导致过滤器工厂无法正常加载。

额外排查小技巧

启动应用时,搜索日志中是否有MyLoggingGatewayFilterFactory相关的注册信息。如果日志里完全没有这个类的加载记录,那肯定是包扫描的问题,回到步骤1解决即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:22:55