springcloud gateway filter中不能使用feign的解决
文章目录背景解决办法1 工具类2、启动类背景在springcloud gateway中使用feign时,网关一般都会用到gatewayFilter.但在gatewayFilter沒法注入feign。这和servlet, filter的加载顺序有关解决办法从spring上下文中获取feign的自定义Bean,然后在正常用1 工具类import org.springframework.beans.Be
·
背景
在springcloud gateway中使用feign时,网关一般都会用到gatewayFilter.但在gatewayFilter沒法注入feign。这和servlet, filter的加载顺序有关
解决办法
从spring上下文中获取feign的自定义Bean,然后在正常用
1 工具类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
public class AutowiredBean{
private static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (AutowiredBean.applicationContext == null) {
AutowiredBean.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
2、启动类
a
@SpringBootApplication
@EnableFeignClients(basePackages = "aaaa.bb")
public class JupyterApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(JupyterApplication.class, args);
AutowiredBean.setApplicationContext(run);
}
}
3、使用
public class AuthorizeGatewayFilter implements GatewayFilter, Ordered {
Logger logger = LoggerFactory.getLogger(AuthorizeGatewayFilter.class);
private static String HEADER_KEY = "token";
@Override
public int getOrder() {
return 100;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//关键看这里,在用的时候在获取bean
JupyterAuthService jupyterAuthService = AutowiredBean.getBean(JupyterAuthService.class);
String record = jupyterAuthService.record();
return chain.filter(exchange);
}
}
更多推荐
已为社区贡献4条内容
所有评论(0)