So I am new to spring cloud gateway and have just started playing around with it . I was going through the documentation and stumbled upon how to create a custom filter.
https://cloud.spring.io/spring-cloud-gateway/reference/html/#developer-guide
So this is my code for creating a custom filter -
@Component
public class CustomPreFilterFactory extends AbstractGatewayFilterFactory<CustomPreFilterFactory.Config> {
public static class Config {
//Put the configuration properties for your filter here
}
@Override
public GatewayFilter apply(Config config) {
return (exchange,chain) ->{
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
System.out.println("Request came in custom pre filter");
return chain.filter(exchange.mutate().request(builder.build()).build());
};
}
}
Now , I am using java route api provided by gateway for configuring my routes , so this is my route code -
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder routeLocatorBuilder)
{
return routeLocatorBuilder.routes()
.route( p -> p.path("/hello").uri("http://localhost:8081"))
.build();
}
Now , I want to know how to add the custom filter factory which i just created to the route defined above programmatically .
I have looked at the following examples where they register a custom filter factory -
1. https://www.javainuse.com/spring/cloud-filter
2. https://medium.com/@niral22/spring-cloud-gateway-tutorial-5311ddd59816
Both of them create routes using properties rather than using the route api .
Any help is much appreciated.