Feign调用第三方,想要单独的拦截器,但是变为全局拦截器
原代码:
feign
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;@RefreshScope
@FeignClient(value = "ThirdClient", url = "http://third.url.com", configuration = ThirdClientFeignInterceptor .class)
public interface ThirdClient {@PostMapping("/api/xxx")Object thirdApi(@RequestBody Object request);
}
feign对应的拦截器
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class ThirdClientFeignInterceptor implements RequestInterceptor {@Autowiredprivate HeaderConfig headerConfig;@Overridepublic void apply(RequestTemplate template) {template.header("token", headerConfig.getToken());}
}
结果发现这个拦截器是全局的拦截器,但我只想调用ThirdClient下面接口的时候才走这个拦截器。需要改成下面这样:
feign对应的拦截器改成下面这样:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;@Slf4j
public class MyFeignInterceptor implements RequestInterceptor {@Resourceprivate HeaderConfig headerConfig;@Overridepublic void apply(RequestTemplate template) {template.header("token", headerConfig.getToken());}
}
原因:
没有@Component,就不会被放入全局拦截器中!!可能是因为feign的RequestInterceptor有相关逻辑,如果有@Component,则把实现了RequestInterceptor这个接口的所有实现类都识别到,加入全局拦截器中。