Feign 客户端未从库初始化 requestInterceptor

问题描述 投票:0回答:1

在这种奇怪的情况下挣扎了一段时间。 我写了一个库,它定义了一个假客户端,来使用一堆 API。这个客户端定义是我总是从以前的项目中获取的复制粘贴代码,因此是一个工作代码,但不同之处在于,这次包含在库中。

@Bean
public DcApi buildApiManagement(@Autowired ObjectMapper mapper,.....) {
.....

return Feign.builder()
  .contract(new SpringMvcContract())
  .encoder(new JacksonEncoder(mapper))
  .decoder(new JacksonDecoder(mapper))
  .logger(new Slf4jLogger(DcApi.class))
  .logLevel(Logger.Level.BASIC)
  .requestInterceptor(new OAuthInterceptor(x509app, oAuth2Scope))
  .target(DcApi.class, url);
}

拦截器,非常简单:

public static class OAuthInterceptor implements RequestInterceptor {
        private final X509Application x509Application;
        private final String scope;

        public OAuthInterceptor(X509Application x509Application, String scope) {
            this.x509Application = x509Application;
            this.scope = scope;
            log.info("Building OAuthInterceptor.");
        }

        @Override
        public void apply(RequestTemplate template) {
            template.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            template.header(HttpHeaders.AUTHORIZATION, "Bearer " +                this.x509Application.getAccessToken(this.scope));
        }
    }

当在应用程序中使用该库时,如果我在 feign 构建器中使用断点进入调试模式,我会看到拦截器已正确创建(并且如果我从调试器调用直接方法,它就会工作)。反正到了使用API的时候,拦截器就显得空了。

我不知道为什么会发生这种情况,有人可以帮我弄清楚吗?

图书馆用户应用程序中的 API 是来自服务类的

@Autowired

我正在使用

spring-cloud-starter-openfeign-4.1.0
org.springframework.boot-3.2.2

谢谢大家:)

我尝试将 OAuthInterceptor 的定义从静态类移动到 @Bean,但没有成功。我已将 log 添加到 feignclient 定义中,以确保仅创建一次,因为之前将其标记为

@Configuration
,导致双重创建。

spring-boot spring-cloud-feign openfeign
1个回答
0
投票

事实证明,问题是由于我处理拦截器的方式造成的。 将实施更改为

@Bean
public RequestInterceptor interceptor() {
    return requestTemplate -> {
        requestTemplate.header("Content-Type", "application/json");
        requestTemplate.header("Cache-Control", "no-cache");
        requestTemplate.header(HttpHeaders.AUTHORIZATION, "Bearer " + 
        this.x509Application.getAccessToken(this.scope));
        requestTemplate.header("Accept", "application/json");
    };
}

这样做,再加上将X509Application修改为bean,解决了这个问题。

我怀疑发生了这种行为,因为除了我即将创建的这个新的假客户端之外,库中还有另一个客户端,其中定义了一个拦截器作为建议的解决方案:我认为两种定义方式,以某种形式输入溢出。

© www.soinside.com 2019 - 2024. All rights reserved.