背景

在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);
   }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐