如何在Spring Boot Feign Client上定义全局静态标头

Sti*_*imp 2 spring-boot feign

我有一个Spring Boot应用程序,想要创建一个Feign客户端,该客户端具有静态定义的标头值(用于auth,但不用于基本auth)。我找到了@Headers注释,但它似乎在Spring Boot领域中不起作用。我怀疑这与使用SpringMvcContract

这是我要工作的代码:

@FeignClient(name = "foo", url = "http://localhost:4444/feign")
@Headers({"myHeader:value"})
public interface LocalhostClient {
Run Code Online (Sandbox Code Playgroud)

但是它不添加标题。

我用自己的尝试制作了一个干净的Spring Boot应用程序,并将其发布到github上:github示例

我能够使其起作用的唯一方法是将其定义RequestInterceptor为全局bean,但是我不想这样做,因为它会影响其他客户端。

onn*_*web 8

你可以在你的 feign 接口上设置一个特定的配置类,并在那里定义一个 RequestInterceptor bean。例如:

@FeignClient(name = "foo", url = "http://localhost:4444/feign", 
configuration = FeignConfiguration.class)
public interface LocalhostClient {
}

@Configuration
public class FeignConfiguration {

  @Bean
  public RequestInterceptor requestTokenBearerInterceptor() {
    return new RequestInterceptor() {
      @Override
      public void apply(RequestTemplate requestTemplate) {
        // Do what you want to do
      }
    };
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

您还可以通过将标头添加到各个方法中来实现此目的,如下所示:

@RequestMapping(method = RequestMethod.GET, path = "/resource", headers = {"myHeader=value"})
Run Code Online (Sandbox Code Playgroud)

在Feign Client + Spring Cloud(Brixton RC2)中使用@Headers和动态值讨论使用的动态值解决方案@RequestHeader