When one backend service needs data or an action from another, it can call the other service’s REST endpoint. OpenFeign is a declarative HTTP client: you describe the call in a Java interface, and Spring Cloud OpenFeign provides its implementation. section 11.0 section 11.3
The interface acts as a contract for the remote call. Annotations specify the endpoint path, HTTP method, headers and request body. OpenFeign supplies an implementation as a Spring bean, which application code can inject and use without writing the HTTP call itself. section 11.3
To create a Spring Cloud OpenFeign client:
- Add the spring-cloud-starter-openfeign dependency. section 11.3
- Declare an interface annotated with @FeignClient. Give it a client name and configure the service URL. section 11.3
- Annotate each method to describe its HTTP request, including the path and any headers or body. section 11.3
- Enable Feign clients in a configuration class and identify the package containing the interface. Inject the resulting client where it is needed. section 11.3
Calling a payment service
A PaymentsProxy interface declares createPayment with @PostMapping("/payment"), a requestId header and a Payment body. Its @FeignClient annotation identifies the client and reads the service URL from a property. A controller can inject the proxy, generate a request ID and call createPayment as an ordinary Java method. section 11.3
Listing 11.4 Declaring an OpenFeign client interface
@FeignClient(name = "payments", #A
url = "${name.service.url}")
public interface PaymentsProxy {
@PostMapping("/payment") #B
Payment createPayment(
@RequestHeader String requestId, #C
@RequestBody Payment payment); #C
}See how the interface annotations describe the payment request without a method implementation. section 11.3
Listing 11.5 Enabling the OpenFeign clients in the configuration class
@Configuration
@EnableFeignClients( #A
basePackages = "com.example.proxy")
public class ProjectConfig {
}See how configuration enables Feign clients in the proxy package. section 11.3
For a regular, non-reactive Spring application, RestClient is a direct alternative; OpenFeign can make larger, structured service communication easier to manage. WebClient is intended for reactive applications and non-blocking calls. OpenFeign also integrates with Spring Cloud Circuitbreaker and Loadbalancer, though those integrations are not needed for the payment example. section 11.1 section 11.3 section 11.6

