You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Spring Cloud Gateway的Java配置中添加自定义过滤器?

Got it, let's break this down for you. Since you're using Java-based configuration for your Spring Cloud Gateway routes instead of YAML, adding your custom LoggingGlobalPreFilter is straightforward—here's how to do it in two common scenarios:

1. Make your filter a global filter (applies to all routes)

If you want your custom filter to run for every incoming request across all routes, you don’t need to modify your route builder code at all. Just ensure your filter class is managed by the Spring container:

  • Add the @Component annotation to your LoggingGlobalPreFilter class:
@Component
public class LoggingGlobalPreFilter extends LoggingGlobalPreFilter {
    // Your filter logic here
}

Spring Cloud Gateway automatically detects beans that implement GlobalFilter (or extend related base classes like LoggingGlobalPreFilter) and applies them globally to all routes.

2. Apply the filter to specific routes only

If you only want the filter to act on certain routes, you can explicitly add it using the filters() method in your route configuration. Here are two practical options:

Option 1: Instantiate the filter directly

If your filter has no dependencies that need injection, you can create a new instance directly in the route builder:

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route(r -> r.path("/first/**")
                    .filters(f -> f.filter(new LoggingGlobalPreFilter())) // Attach your custom filter here
                    .uri("http://localhost:8222"))
            .route(r -> r.path("/second/**") // Fixed typo from "seconf" to "second"
                    .uri("http://localhost:8333"))
            .build();
}

Option 2: Use a Spring-managed bean (better for dependency injection)

If your filter relies on other Spring-managed components (like a logger, database service, etc.), inject the filter bean into your configuration class first, then reference it:

@Autowired
private LoggingGlobalPreFilter loggingGlobalPreFilter;

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route(r -> r.path("/first/**")
                    .filters(f -> f.filter(loggingGlobalPreFilter)) // Use the injected bean
                    .uri("http://localhost:8222"))
            .route(r -> r.path("/second/**")
                    .uri("http://localhost:8333"))
            .build();
}

Quick note: I fixed a typo in your original route config (/seconf/**/second/**) to prevent unexpected routing issues.

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

火山引擎 最新活动