Source code analysis of Spring Cloud OpenFeign

Posted by powaz on Tue, 04 Jan 2022 23:39:35 +0100

OpenFeign is an upgrade of Spring Cloud based on Feign. Using Feign, you can simply initiate remote calls. All we need to do is add the OpenFeign dependency, add the annotation @ EnableFeignClients on the project startup class, then create the FeignClient client interface, add the corresponding interface method, and then we can initiate the remote call. How did all this happen? Next, let's look at the source code of OpenFeign.

Let's start with the @ EnableFeignClients annotation on the startup class.

public @interface EnableFeignClients {

   String[] value() default {};

   String[] basePackages() default {};

   Class<?>[] basePackageClasses() default {};

   Class<?>[] defaultConfiguration() default {};

   Class<?>[] clients() default {};

Feignclientsregister class is introduced in this annotation. We open this class:

class FeignClientsRegistrar
      implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
    public void registerBeanDefinitions(AnnotationMetadata metadata,
      BeanDefinitionRegistry registry) {
        // Register the default configuration class
        registerDefaultConfiguration(metadata, registry);
        // Register Feign client
        registerFeignClients(metadata, registry);

In this class, you can see an important method, registerBeanDefinitions, which injects Feign default configuration and Feign client into IOC container. Let's first look at registerDefaultConfiguration:

private void registerDefaultConfiguration(AnnotationMetadata metadata,
      BeanDefinitionRegistry registry) {
   Map<String, Object> defaultAttrs = metadata
         .getAnnotationAttributes(EnableFeignClients.class.getName(), true);

   if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
      String name;
      if (metadata.hasEnclosingClass()) {
         name = "default." + metadata.getEnclosingClassName();
      else {
         name = "default." + metadata.getClassName();
      registerClientConfiguration(registry, name,

This method first determines whether the @ EnableFeignClients annotation contains the defaultConfiguration attribute. If it contains the defaultConfiguration attribute, it calls the registerClientConfiguration method to register the configuration class in the container.
Next, let's look at the registerFeignClients method:

public void registerFeignClients(AnnotationMetadata metadata,
      BeanDefinitionRegistry registry) {
   // Scan all classes with FeignClient annotations
   LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
   Map<String, Object> attrs = metadata
   AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
   final Class<?>[] clients = attrs == null ? null
         : (Class<?>[]) attrs.get("clients");
   if (clients == null || clients.length == 0) {
      ClassPathScanningCandidateComponentProvider scanner = getScanner();
      scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));
      Set<String> basePackages = getBasePackages(metadata);
      for (String basePackage : basePackages) {
   else {
      for (Class<?> clazz : clients) {
         candidateComponents.add(new AnnotatedGenericBeanDefinition(clazz));

   // Register FeignClient in IOC container
   for (BeanDefinition candidateComponent : candidateComponents) {
      if (candidateComponent instanceof AnnotatedBeanDefinition) {
         // verify annotated class is an interface
         AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
         AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
               "@FeignClient can only be specified on an interface");

         Map<String, Object> attributes = annotationMetadata

         String name = getClientName(attributes);
         // Register the configuration class specified by a single FeignClient
         registerClientConfiguration(registry, name,

         // Register FeignClient
         registerFeignClient(registry, annotationMetadata, attributes);

This method first scans out all classes annotated with FeignClient, and then registers them in the container one by one. Let's look at the registerFeignClient method again:

private void registerFeignClient(BeanDefinitionRegistry registry,
      AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
   String className = annotationMetadata.getClassName();
   BeanDefinitionBuilder definition = BeanDefinitionBuilder
   definition.addPropertyValue("url", getUrl(attributes));
   definition.addPropertyValue("path", getPath(attributes));
   String name = getName(attributes);
   definition.addPropertyValue("name", name);
   String contextId = getContextId(attributes);
   definition.addPropertyValue("contextId", contextId);
   definition.addPropertyValue("type", className);
   definition.addPropertyValue("decode404", attributes.get("decode404"));
   definition.addPropertyValue("fallback", attributes.get("fallback"));
   definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));

   String alias = contextId + "FeignClient";
   AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
   beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className);

   // has a default, won't be null
   boolean primary = (Boolean) attributes.get("primary");


   String qualifier = getQualifier(attributes);
   if (StringUtils.hasText(qualifier)) {
      alias = qualifier;

   BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
         new String[] { alias });
   BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

This method reads the attribute value configured in FeignClient annotation, focusing on FeignClientFactoryBean. The implementation class of Feign client interface is generated from this factory class. We enter this class:

class FeignClientFactoryBean
      implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {
protected <T> T loadBalance(Feign.Builder builder, FeignContext context,
      HardCodedTarget<T> target) {
   Client client = getOptional(context, Client.class);
   if (client != null) {
      Targeter targeter = get(context, Targeter.class);
      return, builder, context, target);

   throw new IllegalStateException(
         "No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-netflix-ribbon?");

public Object getObject() throws Exception {
   return getTarget();

* @param <T> the target type of the Feign client
* @return a {@link Feign} client created with the specified data and the context
* information
<T> T getTarget() {
   FeignContext context = applicationContext.getBean(FeignContext.class);
   Feign.Builder builder = feign(context);

   if (!StringUtils.hasText(url)) {
      if (!name.startsWith("http")) {
         url = "http://" + name;
      else {
         url = name;
      url += cleanPath();
      return (T) loadBalance(builder, context,
            new HardCodedTarget<>(type, name, url));
   if (StringUtils.hasText(url) && !url.startsWith("http")) {
      url = "http://" + url;
   String url = this.url + cleanPath();
   Client client = getOptional(context, Client.class);
   if (client != null) {
      if (client instanceof LoadBalancerFeignClient) {
         // not load balancing because we have a url,
         // but ribbon is on the classpath, so unwrap
         client = ((LoadBalancerFeignClient) client).getDelegate();
      if (client instanceof FeignBlockingLoadBalancerClient) {
         // not load balancing because we have a url,
         // but Spring Cloud LoadBalancer is on the classpath, so unwrap
         client = ((FeignBlockingLoadBalancerClient) client).getDelegate();
   Targeter targeter = get(context, Targeter.class);
   return (T), builder, context,
         new HardCodedTarget<>(type, name, url));

Only three important methods are shown here. getObject is the method of the factory class production object, which calls the getTarget method. The main business logic of this method is to judge whether the value of url is set in FeignClient annotation. If the url address is set, the request is made according to this address without adding load balancing logic. How can the url be empty, Load balancing is performed according to the service name, and the loadBalance method is called to add load balancing logic.
We continue to look at the loadBalance method. We don't see the specific load balancing logic, but the following two lines of code:

Targeter targeter = get(context, Targeter.class);
return, builder, context, target);

The target here is the object of the hystrixtarger class, which is injected into the automatic configuration class of OpenFeign. Let's look at spring-cloud-OpenFeign-core-2.2.6 RELEASE. Spring.jar package Factories file

 stay FeignAutoConfiguration Class, registered HystrixTargeter of Bean. 

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({ FeignClientProperties.class,
      FeignHttpClientProperties.class })
public class FeignAutoConfiguration {

   @Configuration(proxyBeanMethods = false)
   @ConditionalOnClass(name = "feign.hystrix.HystrixFeign")
   protected static class HystrixFeignTargeterConfiguration {
      public Targeter feignTargeter() {
         return new HystrixTargeter();

   @Configuration(proxyBeanMethods = false)
   protected static class DefaultFeignTargeterConfiguration {
      public Targeter feignTargeter() {
         return new DefaultTargeter();

Let's take a look at the target method of hystrixtarger

public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
      FeignContext context, Target.HardCodedTarget<T> target) {
   if (!(feign instanceof feign.hystrix.HystrixFeign.Builder)) {
   feign.hystrix.HystrixFeign.Builder builder = (feign.hystrix.HystrixFeign.Builder) feign;
   String name = StringUtils.isEmpty(factory.getContextId()) ? factory.getName()
         : factory.getContextId();
   SetterFactory setterFactory = getOptional(name, context, SetterFactory.class);
   if (setterFactory != null) {
   Class<?> fallback = factory.getFallback();
   if (fallback != void.class) {
      return targetWithFallback(name, context, target, builder, fallback);
   Class<?> fallbackFactory = factory.getFallbackFactory();
   if (fallbackFactory != void.class) {
      return targetWithFallbackFactory(name, context, target, builder,


In this method, you can add fusing fallback logic, and then execute feign hystrix. HystrixFeign. The target method of builder, which has multiple overloaded methods,

public <T> T target(Target<T> target, T fallback) {
  return build(fallback != null ? new FallbackFactory.Default<T>(fallback) : null)

public <T> T target(Target<T> target, FallbackFactory<? extends T> fallbackFactory) {
  return build(fallbackFactory).newInstance(target);

public <T> T target(Class<T> apiType, String url, T fallback) {
  return target(new Target.HardCodedTarget<T>(apiType, url), fallback);

public <T> T target(Class<T> apiType,
                    String url,
                    FallbackFactory<? extends T> fallbackFactory) {
  return target(new Target.HardCodedTarget<T>(apiType, url), fallbackFactory);

Its parent class also has

public <T> T target(Class<T> apiType, String url) {
  return target(new HardCodedTarget<T>(apiType, url));

public <T> T target(Target<T> target) {
  return build().newInstance(target);

The target method calls the build method again. Let's take a look at feign hystrix. HystrixFeign. Build method of builder

/** Configures components needed for hystrix integration. */
Feign build(final FallbackFactory<?> nullableFallbackFactory) {
  super.invocationHandlerFactory(new InvocationHandlerFactory() {
    public InvocationHandler create(Target target,
                                    Map<Method, MethodHandler> dispatch) {
      return new HystrixInvocationHandler(target, dispatch, setterFactory,
  super.contract(new HystrixDelegatingContract(contract));

Finally, the build method of the parent class is called

public Feign build() {
    Client client = Capability.enrich(this.client, capabilities);
    Retryer retryer = Capability.enrich(this.retryer, capabilities);
    List<RequestInterceptor> requestInterceptors =
        .map(ri -> Capability.enrich(ri, capabilities))
    Logger logger = Capability.enrich(this.logger, capabilities);
    Contract contract = Capability.enrich(this.contract, capabilities);
    Options options = Capability.enrich(this.options, capabilities);
    Encoder encoder = Capability.enrich(this.encoder, capabilities);
    Decoder decoder = Capability.enrich(this.decoder, capabilities);
    InvocationHandlerFactory invocationHandlerFactory =
        Capability.enrich(this.invocationHandlerFactory, capabilities);
    QueryMapEncoder queryMapEncoder = Capability.enrich(this.queryMapEncoder, capabilities);

    SynchronousMethodHandler.Factory synchronousMethodHandlerFactory =
        new SynchronousMethodHandler.Factory(client, retryer, requestInterceptors, logger,
            logLevel, decode404, closeAfterDecode, propagationPolicy, forceDecoding);
    ParseHandlersByName handlersByName =
        new ParseHandlersByName(contract, options, encoder, decoder, queryMapEncoder,
            errorDecoder, synchronousMethodHandlerFactory);
    return new ReflectiveFeign(handlersByName, invocationHandlerFactory, queryMapEncoder);

The final return of the build method is the object of the reflective feign class. Let's look at its newInstance method

public <T> T newInstance(Target<T> target) {
  Map<String, MethodHandler> nameToHandler = targetToHandlersByName.apply(target);
  Map<Method, MethodHandler> methodToHandler = new LinkedHashMap<Method, MethodHandler>();
  List<DefaultMethodHandler> defaultMethodHandlers = new LinkedList<DefaultMethodHandler>();

  for (Method method : target.type().getMethods()) {
    if (method.getDeclaringClass() == Object.class) {
    } else if (Util.isDefault(method)) {
      DefaultMethodHandler handler = new DefaultMethodHandler(method);
      methodToHandler.put(method, handler);
    } else {
      methodToHandler.put(method, nameToHandler.get(Feign.configKey(target.type(), method)));
  InvocationHandler handler = factory.create(target, methodToHandler);
  // Generate dynamic proxy object
  T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(),
      new Class<?>[] {target.type()}, handler);

  for (DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
  return proxy;

This method finally generates the proxy object corresponding to Feign client interface, and completes the remote call through this proxy object during operation.

Topics: Spring Cloud feign OpenFeign