How to Specify custom filter in application.yml Spring Cloud Gateway
Instead of implementing GatewayFilter you should implement GatewayFilterFactory
and make it a Component:
@Component
public class MyGatewayFilter implements GatewayFilterFactory {
Then you can refer to it by the bean name in your route.
filters:
- MyGatewayFilter
The documentation on this isn't very good at the moment. I was only able to figure this out by looking at the source code for spring-cloud-gateway on github
You need to implement GatewayFilterFactory
@Component
public class DemoGatewayFilter implements GatewayFilterFactory<DemoGatewayFilter.Config> {
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
System.out.println("gateway filter name "+config.getName());
return chain.filter(exchange);
};
}
@Override
public Config newConfig() {
return new Config("DemoGatewayFilter");
}
public static class Config {
public Config(String name){
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
and in application.yml file
spring:
application:
cloud:
gateway:
routes:
- id: MayApplication
uri: http://myapplication:8080
predicates:
- Path=/apipath/to/filter/**
filters:
- DemoGatewayFilter