OpenFeign Installation Guide

Project Dependency Configuration

Maven Dependencies

<!-- Spring Cloud OpenFeign Starter -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!-- Required for load balancing support -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

Gradle Dependencies

implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer'

Version Management

Use Spring Cloud BOM to manage versions in pom.xml:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2022.0.4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Basic Configuration

Enable Feign Clients

Add @EnableFeignClients annotation to your main application class:

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

Specify Client Scan Packages

If your Feign client interfaces are not in the same package as your main application class, specify scan packages:

@SpringBootApplication
@EnableFeignClients(basePackages = "com.example.clients")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Or explicitly list clients:

@SpringBootApplication
@EnableFeignClients(clients = {UserServiceClient.class, OrderServiceClient.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Creating Feign Clients

Basic Usage

@FeignClient(name = "user-service")
public interface UserService {
    
    @GetMapping("/users/{id}")
    User getUser(@PathVariable("id") Long id);
    
    @GetMapping("/users")
    List<User> getAllUsers();
    
    @PostMapping("/users")
    User createUser(@RequestBody User user);
    
    @PutMapping("/users/{id}")
    User updateUser(@PathVariable("id") Long id, @RequestBody User user);
    
    @DeleteMapping("/users/{id}")
    void deleteUser(@PathVariable("id") Long id);
}

Using URL Attribute

If you don't need service discovery, specify URL directly:

@FeignClient(name = "external-api", url = "https://api.example.com")
public interface ExternalApiClient {
    @GetMapping("/data")
    ApiResponse getData();
}

Supported Annotations

OpenFeign supports the following Spring MVC annotations:

  • HTTP Method Annotations: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping
  • Path Variables: @PathVariable
  • Request Parameters: @RequestParam
  • Request Body: @RequestBody
  • Request Headers: @RequestHeader
  • Cookies: @CookieValue

Complex Parameter Examples

@FeignClient(name = "order-service")
public interface OrderService {
    
    // Path variable + request parameter
    @GetMapping("/orders/{userId}")
    List<Order> getOrdersByUser(
        @PathVariable("userId") Long userId,
        @RequestParam("status") String status,
        @RequestParam(value = "page", defaultValue = "0") int page
    );
    
    // Request body + request header
    @PostMapping("/orders")
    @Headers("X-API-Version: 2.0")
    Order createOrder(
        @RequestBody CreateOrderRequest request,
        @RequestHeader("Authorization") String token
    );
    
    // Query parameter Map
    @GetMapping("/orders/search")
    List<Order> searchOrders(@SpringQueryMap SearchCriteria criteria);
}

Using Feign Clients

Injecting in Service

@Service
public class OrderProcessingService {
    
    private final UserService userService;
    private final OrderService orderService;
    
    public OrderProcessingService(UserService userService, OrderService orderService) {
        this.userService = userService;
        this.orderService = orderService;
    }
    
    public Order processOrder(Long userId, CreateOrderRequest request) {
        // Validate user
        User user = userService.getUser(userId);
        if (user == null) {
            throw new UserNotFoundException("User not found: " + userId);
        }
        
        // Create order
        return orderService.createOrder(request, "Bearer " + generateToken());
    }
    
    private String generateToken() {
        // Generate authentication token
        return "token";
    }
}

Using in Controller

@RestController
@RequestMapping("/api/v1")
public class OrderController {
    
    private final OrderService orderService;
    
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }
    
    @GetMapping("/orders/{id}")
    public ResponseEntity<Order> getOrder(@PathVariable Long id) {
        Order order = orderService.getOrder(id);
        return ResponseEntity.ok(order);
    }
    
    @PostMapping("/orders")
    public ResponseEntity<Order> createOrder(@RequestBody CreateOrderRequest request) {
        Order order = orderService.createOrder(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(order);
    }
}

Configuration Properties

Basic Configuration

Configure in application.yml:

spring:
  cloud:
    openfeign:
      client:
        config:
          default:
            connect-timeout: 5000
            read-timeout: 5000
            logger-level: basic
          user-service:
            connect-timeout: 3000
            read-timeout: 10000
            logger-level: full

Log Level Configuration

logging:
  level:
    com.example.clients.UserService: DEBUG

Supported log levels:

  • NONE: No logging (default)
  • BASIC: Log only request method, URL, response status code, and execution time
  • HEADERS: Log basic information along with request and response headers
  • FULL: Log headers, body, and metadata for both requests and responses

Error Handling

Custom Error Decoder

@Component
public class CustomErrorDecoder implements ErrorDecoder {
    
    private final ErrorDecoder defaultErrorDecoder = new Default();
    
    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() >= 400 && response.status() < 500) {
            return new ClientException("Client error: " + response.status());
        } else if (response.status() >= 500) {
            return new ServerException("Server error: " + response.status());
        }
        return defaultErrorDecoder.decode(methodKey, response);
    }
}

Register in Configuration

@Configuration
public class FeignConfig {
    
    @Bean
    public ErrorDecoder errorDecoder() {
        return new CustomErrorDecoder();
    }
}

Testing Feign Clients

Unit Testing

@ExtendWith(MockitoExtension.class)
class OrderProcessingServiceTest {
    
    @Mock
    private UserService userService;
    
    @Mock
    private OrderService orderService;
    
    @InjectMocks
    private OrderProcessingService orderProcessingService;
    
    @Test
    void shouldProcessOrderSuccessfully() {
        // Given
        Long userId = 1L;
        User user = new User(userId, "John Doe");
        CreateOrderRequest request = new CreateOrderRequest();
        Order expectedOrder = new Order(1L, userId);
        
        when(userService.getUser(userId)).thenReturn(user);
        when(orderService.createOrder(any(), anyString())).thenReturn(expectedOrder);
        
        // When
        Order result = orderProcessingService.processOrder(userId, request);
        
        // Then
        assertThat(result).isEqualTo(expectedOrder);
        verify(userService).getUser(userId);
        verify(orderService).createOrder(request, anyString());
    }
}

Integration Testing

@SpringBootTest
@AutoConfigureTestDatabase
class FeignIntegrationTest {
    
    @Autowired
    private UserService userService;
    
    @Test
    void shouldGetUserFromRemoteService() {
        // When
        User user = userService.getUser(1L);
        
        // Then
        assertThat(user).isNotNull();
        assertThat(user.getId()).isEqualTo(1L);
    }
}

With these steps, you can quickly get started with OpenFeign to simplify microservice communication. The following chapters will introduce more advanced features and best practices.