Cloud Native 20 min read

OpenFeign Deep Dive: Architecture, Dynamic Proxy, and Spring Cloud Integration

This article thoroughly explains OpenFeign’s core architecture, detailing its original Feign foundation, seven essential components, dynamic proxy generation, HTTP call execution flow, and how Spring Cloud seamlessly integrates and configures OpenFeign through annotations, factories, and property-based settings.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
OpenFeign Deep Dive: Architecture, Dynamic Proxy, and Spring Cloud Integration

Hello everyone, I am Su San.

Previously I wrote two articles about the architecture principles of OpenFeign and Ribbon, core components of Spring Cloud, but I now feel those articles could be improved.

I'm preparing a booklet on Spring Cloud component architectures, so I will rewrite those articles, starting with OpenFeign.

The article is divided into four parts:

What does the original Feign look like?

What are Feign's core components and execution chain?

How does Spring Cloud integrate Feign?

What configuration options does OpenFeign have and their priority?

Let's dive into OpenFeign's core architecture.

What does the original Feign look like?

Using Feign in daily development is simple, consisting of three steps.

Step 1: Add dependency

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
  <version>2.2.5.RELEASE</version>
</dependency>

Step 2: Add @EnableFeignClients annotation to the main class

@SpringBootApplication
@EnableFeignClients
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Step 3: Define a FeignClient interface

@FeignClient(name = "order")
@RequestMapping("/order")
public interface OrderApiClient {
    @GetMapping
    Order queryOrder(@RequestParam("orderId") Long orderId);
}

Inject OrderApiClient where needed and use it directly.

Feign was originally open‑sourced by Netflix; Spring Cloud wraps it and calls it OpenFeign.

The article may sometimes not strictly distinguish between Feign and OpenFeign; just understand the general meaning.

Feign can also be used directly without Spring Cloud:

public interface OrderApiClient {
    @RequestLine("GET /order/{orderId}")
    Order queryOrder(@Param("orderId") Long orderId);
}

Create the client manually:

public class FeignDemo {
    public static void main(String[] args) {
        OrderApiClient orderApiClient = Feign.builder()
            .target(OrderApiClient.class, "http://localhost:8088");
        orderApiClient.queryOrder(9527L);
    }
}

Feign's essence: Dynamic proxy + seven core components

Feign builds a JDK dynamic proxy; the proxy parses method annotations and parameters to construct HTTP request data.

During request construction, it determines URL, body, headers, etc., then sends the HTTP request, receives the response, and converts the response body to the method's return type.

The dynamic proxy relies on several core components, illustrated below:

Key components include:

1. Contract

Contract parses method annotations and parameters, generating a MethodMetadata object that maps HTTP request parts to method arguments. Spring Cloud provides its own implementation to support Spring MVC annotations.

2. Encoder

Encoder serializes request body parameters into byte arrays. Spring’s SpringEncoder can handle arbitrary object types.

3. Decoder

Decoder deserializes the response body back into the method’s return type; Spring provides SpringDecoder for flexible handling.

4. Client

Client executes the HTTP request. The default uses HttpURLConnection, but Spring Cloud can replace it with Apache HttpClient or OkHttp implementations.

5. InvocationHandlerFactory

Creates the InvocationHandler that contains the core logic for the dynamic proxy.

6. RequestInterceptor

Allows modification of the request before it is sent, e.g., adding authentication tokens.

@Component
public class TokenRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        template.header("token", "token值");
    }
}

7. Retryer

Handles retry logic; Spring Cloud disables the default retryer and provides its own implementation.

Feign core runtime analysis

The execution flow consists of:

FeignInvocationHandler locates the corresponding SynchronousMethodHandler and invokes it.

Method metadata and arguments are used to build a RequestTemplate, with the body encoded by the Encoder.

RequestInterceptors can modify the template.

The template is converted to a Request.

The Client sends the HTTP request and receives a Response.

The Decoder converts the response body to the method’s return type.

If a Retryer is configured, it operates during the request phase.

How Spring Cloud integrates Feign

Spring Cloud registers Feign clients via @EnableFeignClients, which imports FeignClientsRegistrar. This registrar scans for interfaces annotated with @FeignClient, creates FeignClientFactoryBean definitions, and registers them as beans.

Each FeignClientFactoryBean implements FactoryBean; during bean creation Spring calls getObject(), which ultimately invokes Feign.builder() to create the dynamic proxy, using Spring‑provided component implementations.

OpenFeign configuration methods and priority

Four ways to configure OpenFeign, ordered by priority (high to low):

Configuration properties (highest by default; can be lowered with feign.client.default-to-properties=false).

Configuration class annotated with @Configuration in the main application context (global, highest priority). @FeignClient(configuration=...) on a specific client (applies only to that client, higher than @EnableFeignClients default config). @EnableFeignClients(defaultConfiguration=...) (global, lower than the previous two).

Examples of each method are provided in the article.

Summary

The article covered OpenFeign’s core architecture, dynamic proxy generation, runtime execution, Spring Cloud integration, and the various configuration mechanisms with their precedence.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMicroservicesSpring CloudDynamic ProxyOpenFeign
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.