Declarative HTTP clients: OpenFeign and HTTP interfaces
A declarative client turns a Java interface into calls to a remote HTTP API, so service code calls methods instead of building requests. Spring Cloud OpenFeign made this popular, but it is now feature-complete, and Spring Framework's own HTTP interface clients replace it. This page runs those interface clients in Spring Boot 4, with timeouts, headers and error mapping, and shows the OpenFeign setup and how to migrate.
Contents
What a declarative HTTP client does
Calling another service by hand means building a URL, setting headers, sending the request, checking the status and converting the JSON body, for every endpoint. A declarative client moves all of that into a framework. You write an interface whose methods carry annotations describing the HTTP request, and the framework generates an implementation at run time, a dynamic proxy. Calling inventory.get("book")GET /items/book
Netflix's Feign library introduced the style, and Spring Cloud OpenFeign integrated it with Spring MVC annotations, Spring's message converters and Spring Cloud's load balancer. Spring Framework 6.0 then added its own version, HTTP interface clients, built on RestClientWebClient
| Client | Since | Annotations | Status |
|---|---|---|---|
| Spring Cloud OpenFeign | Its own project since Spring Cloud Finchley (2018) | @FeignClient | Feature-complete since 2022.0, bug fixes only |
HTTP interface with HttpServiceProxyFactory | Spring Framework 6.0 | @HttpExchange@GetExchange | Current |
HTTP service client groups, @ImportHttpServices | Spring Framework 7.0, Spring Boot 4.0 | Same, plus configuration properties per group | Current, recommended |
All four programs below run with Spring Boot 4.1 and Spring Framework 7.0; each starts its own remote service in the same process. The fourth uses Spring Cloud OpenFeign 5.0.3 with Spring Cloud LoadBalancer, from the Spring Cloud 2025.1 release train, whose 2025.1.2 release added Boot 4.1 support. The page's classpath holds spring-boot-starter-webmvcspring-boot-starter-restclientspring-cloud-starter-openfeignspring-cloud-starter-loadbalancer
An HTTP service client in Spring Boot 4
An order service needs three operations from an inventory service: read an item, search by stock and add an item. The program runs the inventory service as a real Spring Boot application on a random port, then starts the order service as a second application that calls it through an interface:
package demo.feign.declarative;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
import org.springframework.web.service.registry.ImportHttpServices;
public class DeclarativeClient {
record Item(String sku, int stock) {
}
// ---- the remote service: an inventory API running in its own application ----
@RestController
static class InventoryController {
private final Map<String, Item> items = new ConcurrentHashMap<>(
Map.of("book", new Item("book", 7)));
@GetMapping("/items/{sku}")
Item get(@PathVariable String sku) {
Item item = items.get(sku);
if (item == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
return item;
}
@GetMapping("/items")
Map<String, Item> search(@RequestParam int minStock) {
Map<String, Item> result = new ConcurrentHashMap<>();
items.values().stream().filter(i -> i.stock() >= minStock)
.forEach(i -> result.put(i.sku(), i));
return result;
}
@PostMapping("/items")
ResponseEntity<Item> add(@RequestBody Item item) {
items.put(item.sku(), item);
return ResponseEntity.status(HttpStatus.CREATED).body(item);
}
}
// configured without component scanning, so that the two applications in this
// one file do not pick up each other's beans
@SpringBootConfiguration
@EnableAutoConfiguration
@Import(InventoryController.class)
static class InventoryService {
}
// ---- the client side: a declarative HTTP interface instead of a Feign client ----
@HttpExchange("/items")
interface InventoryClient {
@GetExchange("/{sku}")
Item get(@PathVariable String sku);
@GetExchange
Map<String, Item> search(@RequestParam int minStock);
@PostExchange
ResponseEntity<Item> add(@RequestBody Item item);
}
@SpringBootConfiguration
@EnableAutoConfiguration
@ImportHttpServices(group = "inventory", types = InventoryClient.class)
static class OrderService {
}
public static void main(String[] args) {
String[] quiet = {"--spring.main.banner-mode=off", "--logging.level.root=WARN"};
try (var server = new SpringApplication(InventoryService.class).run(
concat(quiet, "--server.port=0"));
var client = new SpringApplication(OrderService.class).run(concat(quiet,
"--spring.main.web-application-type=none",
"--spring.http.serviceclient.inventory.base-url=http://localhost:"
+ ((WebServerApplicationContext) server).getWebServer().getPort()))) {
InventoryClient inventory = client.getBean(InventoryClient.class);
System.out.println("Client bean: a JDK proxy = "
+ Proxy.isProxyClass(inventory.getClass()));
System.out.println("get(\"book\") -> " + inventory.get("book"));
ResponseEntity<Item> created = inventory.add(new Item("pen", 40));
System.out.println("add(pen, 40) -> " + created.getStatusCode().value()
+ " " + created.getBody());
System.out.println("search(minStock=10) -> " + inventory.search(10));
try {
inventory.get("lamp");
} catch (HttpClientErrorException.NotFound e) {
System.out.println("get(\"lamp\") -> " + e.getClass().getSimpleName()
+ ": " + e.getStatusCode());
}
}
}
static String[] concat(String[] base, String... more) {
String[] all = Arrays.copyOf(base, base.length + more.length);
System.arraycopy(more, 0, all, base.length, more.length);
return all;
}
}
Client bean: a JDK proxy = true
get("book") -> Item[sku=book, stock=7]
add(pen, 40) -> 201 Item[sku=pen, stock=40]
search(minStock=10) -> {pen=Item[sku=pen, stock=40]}
get("lamp") -> NotFound: 404 NOT_FOUND
registered a bean for the interface, and the bean is a JDK dynamic proxy. No implementation class exists in the code.@ImportHttpServices(group = "inventory", types = InventoryClient.class)- The property
gave the group its address. Every interface in the group shares thatspring.http.serviceclient.inventory.base-url configuration.RestClient sentget("book") : the type-levelGET /items/book and the method's@HttpExchange("/items") were joined, and@GetExchange("/{sku}") filled in the placeholder. The JSON came back as an@PathVariable record.Item returned aadd , so the caller saw the status, 201, as well as the body. A method that returns the body type alone gets only the body.ResponseEntity sentsearch(10) as a query parameter and returned onlyminStock=10 , the item with at least 10 in stock.pen- For the missing
, the 404 becamelamp , the same exceptionHttpClientErrorException.NotFound throws for any 4xx response.RestClient
The method annotations reuse Spring MVC's @PathVariable@RequestParam@RequestHeader@RequestBody@SpringBootConfiguration@EnableAutoConfiguration@Import@SpringBootApplication
Timeouts, headers and error mapping
Every remote client needs a timeout, usually some common headers, and a decision about what each error status means to the caller. This program configures all three for the inventory
package demo.feign.policies;
import java.util.Arrays;
import java.util.function.Supplier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.support.RestClientHttpServiceGroupConfigurer;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.registry.ImportHttpServices;
public class ClientPolicies {
static class ItemNotFoundException extends RuntimeException {
ItemNotFoundException(String message) {
super(message);
}
}
// ---- the remote service ----
@RestController
static class InventoryController {
@GetMapping("/items/{sku}")
String get(@PathVariable String sku) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no item " + sku);
}
@GetMapping("/slow")
String slow() throws InterruptedException {
Thread.sleep(1500);
return "finally";
}
@GetMapping("/busy")
String busy() {
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE);
}
@GetMapping("/whoami")
String whoami(@RequestHeader("X-Tenant") String tenant,
@RequestHeader(HttpHeaders.AUTHORIZATION) String auth) {
return "tenant=" + tenant + ", authorization=" + auth;
}
}
@SpringBootConfiguration
@EnableAutoConfiguration
@Import(InventoryController.class)
static class InventoryService {
}
// ---- the client ----
interface InventoryClient {
@GetExchange("/items/{sku}")
String get(@PathVariable String sku);
@GetExchange("/slow")
String slow();
@GetExchange("/busy")
String busy();
@GetExchange("/whoami")
String whoami();
}
@SpringBootConfiguration
@EnableAutoConfiguration
@ImportHttpServices(group = "inventory", types = InventoryClient.class)
static class OrderService {
// code-level settings for every client in the "inventory" group
@Bean
RestClientHttpServiceGroupConfigurer inventoryPolicies() {
return groups -> groups.filterByName("inventory").forEachClient((group, builder) ->
builder.requestInterceptor((request, body, execution) -> {
request.getHeaders().setBearerAuth("token-123");
return execution.execute(request, body);
}).defaultStatusHandler(status -> status.value() == 404, (req, res) -> {
throw new ItemNotFoundException("not found: " + req.getURI().getPath());
}));
}
}
static void call(String label, Supplier<String> call) {
try {
System.out.println(label + " -> " + call.get());
} catch (HttpStatusCodeException e) {
// the message also holds the error body, with a timestamp: print the status only
System.out.println(label + " -> " + e.getClass().getSimpleName() + ": "
+ e.getStatusCode());
} catch (ResourceAccessException e) {
System.out.println(label + " -> " + e.getClass().getSimpleName() + ", caused by "
+ e.getCause().getClass().getSimpleName());
} catch (RuntimeException e) {
System.out.println(label + " -> " + e.getClass().getSimpleName() + ": "
+ e.getMessage());
}
}
public static void main(String[] args) {
String[] quiet = {"--spring.main.banner-mode=off", "--logging.level.root=WARN"};
try (var server = SpringApplication.run(InventoryService.class,
concat(quiet, "--server.port=0"));
var client = SpringApplication.run(OrderService.class, concat(quiet,
"--spring.main.web-application-type=none",
"--spring.http.serviceclient.inventory.base-url=http://localhost:"
+ ((WebServerApplicationContext) server).getWebServer().getPort(),
"--spring.http.serviceclient.inventory.read-timeout=500ms",
"--spring.http.serviceclient.inventory.default-header.X-Tenant=shop-eu"))) {
InventoryClient inventory = client.getBean(InventoryClient.class);
call("whoami() ", inventory::whoami);
call("get(\"lamp\")", () -> inventory.get("lamp"));
call("busy() ", inventory::busy);
long start = System.nanoTime();
call("slow() ", inventory::slow);
System.out.println("slow() gave up after about "
+ Math.round((System.nanoTime() - start) / 1e8) * 100 + " ms");
System.out.println("503 is an HttpServerErrorException: "
+ catches(inventory::busy, HttpServerErrorException.class)
+ ", timeout is a ResourceAccessException: "
+ catches(inventory::slow, ResourceAccessException.class));
}
}
static boolean catches(Runnable call, Class<? extends RuntimeException> type) {
try {
call.run();
return false;
} catch (RuntimeException e) {
return type.isInstance(e);
}
}
static String[] concat(String[] base, String... more) {
String[] all = Arrays.copyOf(base, base.length + more.length);
System.arraycopy(more, 0, all, base.length, more.length);
return all;
}
}
whoami() -> tenant=shop-eu, authorization=Bearer token-123
get("lamp") -> ItemNotFoundException: not found: /items/lamp
busy() -> ServiceUnavailable: 503 SERVICE_UNAVAILABLE
slow() -> ResourceAccessException, caused by HttpTimeoutException
slow() gave up after about 500 ms
503 is an HttpServerErrorException: true, timeout is a ResourceAccessException: true
shows both headers arriving:whoami() from theX-Tenant: shop-eu property, anddefault-header from the request interceptor added by theBearer token-123 .RestClientHttpServiceGroupConfigurer- The 404 for
became the application's ownlamp , because the group'sItemNotFoundException claimed status 404. The caller can catch a domain exception instead of an HTTP one.defaultStatusHandler - The 503 kept the default mapping,
, a subclass ofHttpServerErrorException.ServiceUnavailable . That is the exception to configure a retry for, as on theHttpServerErrorExceptionresilience page. gave up after about 500 ms, the group'sslow() , although the server needed 1.5 seconds. The client raisedread-timeout , caused byResourceAccessException from the JDK'sHttpTimeoutException , which Spring Boot uses when no other HTTP client library is on the classpath.HttpClient
Without a read-timeoutspring.http.serviceclient.<group>.read-timeoutconnect-timeoutspring.http.clients.read-timeoutspring.http.client.*spring.http.clients.*
The same client without Spring Boot
The interface clients are part of Spring Framework, so they also work without Spring Boot, and in Spring Boot 3 applications that do not have @ImportHttpServices
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
public class ProxyFactoryClient {
interface GreetingClient {
@GetExchange("/greet/{name}")
String greet(@PathVariable String name);
}
public static void main(String[] args) throws Exception {
// a tiny remote service built with the JDK's own HTTP server
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/greet/", exchange -> {
String name = exchange.getRequestURI().getPath().substring("/greet/".length());
byte[] body = ("hello " + name).getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
try {
// the same interface, wired by hand: Spring Framework only, no Spring Boot
String baseUrl = "http://localhost:" + server.getAddress().getPort();
RestClient rest = RestClient.create(baseUrl);
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(rest))
.build();
GreetingClient client = factory.createClient(GreetingClient.class);
System.out.println(client.greet("ana"));
System.out.println(client.greet("ben"));
} finally {
server.stop(0);
}
}
}
hello ana
hello ben
connects the proxy factory to aRestClientAdapter , which does the HTTP work;RestClient does the same forWebClientAdapter , for interfaces that returnWebClient orMono .Flux produced the proxy, and both calls went to the server and returned its text.createClient
Before Spring Framework 7, every client was declared this way, as a @Bean@ImportHttpServicesRestClient
Spring Cloud OpenFeign
Existing applications often use OpenFeign, and it still works with Spring Boot 4 through the Spring Cloud 2025.1 release train. Its setup is the spring-cloud-starter-openfeigninventory-1inventory-2@FeignClient
package demo.feign.loadbalanced;
import feign.FeignException;
import feign.RetryableException;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
public class FeignLoadBalanced {
public record Item(String sku, int stock, String servedBy) {
}
// the remote service, started twice
@RestController
static class InventoryController {
private final String instance;
InventoryController(Environment env) {
this.instance = env.getProperty("instance");
}
@GetMapping("/items/{sku}")
Item get(@PathVariable("sku") String sku) throws InterruptedException {
if (sku.equals("unknown")) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
if (sku.equals("slow")) {
Thread.sleep(2000);
}
return new Item(sku, 7, instance);
}
@PostMapping("/items")
Item add(@RequestBody Item item) {
return new Item(item.sku(), item.stock(), instance);
}
}
@SpringBootConfiguration
@EnableAutoConfiguration
@Import(InventoryController.class)
static class InventoryApplication {
}
// the client: no URL, so "inventory" is a service name for the load balancer
@FeignClient(name = "inventory")
public interface InventoryClient {
@GetMapping("/items/{sku}")
Item get(@PathVariable("sku") String sku);
@PostMapping("/items")
Item add(@RequestBody Item item);
}
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableFeignClients(clients = InventoryClient.class)
static class OrdersApplication {
}
public static void main(String[] args) {
String[] quiet = {"--spring.main.banner-mode=off", "--logging.level.root=WARN",
"--logging.level.org.springframework.cloud.loadbalancer=ERROR"};
try (var first = start(InventoryApplication.class, quiet, "--server.port=0",
"--instance=inventory-1");
var second = start(InventoryApplication.class, quiet, "--server.port=0",
"--instance=inventory-2");
var orders = start(OrdersApplication.class, quiet,
"--spring.main.web-application-type=none",
// a fixed instance list in place of a registry such as Eureka
"--spring.cloud.discovery.client.simple.instances.inventory[0].uri="
+ url(first),
"--spring.cloud.discovery.client.simple.instances.inventory[1].uri="
+ url(second),
"--spring.cloud.openfeign.client.config.inventory.read-timeout=500")) {
InventoryClient inventory = orders.getBean(InventoryClient.class);
System.out.println("client is a JDK proxy: "
+ Proxy.isProxyClass(inventory.getClass()));
Item book = inventory.get("book");
System.out.println("GET book -> " + book.sku() + ", stock " + book.stock());
Item pen = inventory.add(new Item("pen", 3, null));
System.out.println("POST pen -> " + pen.sku() + ", stock " + pen.stock());
// round-robin starts at a random instance, so count the answers
Map<String, Integer> servedBy = new TreeMap<>();
for (int i = 0; i < 6; i++) {
servedBy.merge(inventory.get("book").servedBy(), 1, Integer::sum);
}
System.out.println("6 calls -> " + servedBy);
try {
inventory.get("unknown");
} catch (FeignException.NotFound e) {
System.out.println("GET unknown -> " + e.getClass().getSimpleName()
+ ", status " + e.status());
}
try {
inventory.get("slow");
} catch (RetryableException e) {
System.out.println("GET slow -> " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
}
}
static ConfigurableApplicationContext start(Class<?> app, String[] quiet, String... more) {
return new SpringApplication(app).run(
Stream.concat(Stream.of(quiet), Stream.of(more)).toArray(String[]::new));
}
static String url(ConfigurableApplicationContext app) {
return "http://localhost:" + app.getEnvironment().getProperty("local.server.port");
}
}
client is a JDK proxy: true
GET book -> book, stock 7
POST pen -> pen, stock 3
6 calls -> {inventory-1=3, inventory-2=3}
GET unknown -> NotFound, status 404
GET slow -> RetryableException: Read timed out executing GET http://inventory/items/slow
- As with the HTTP service client, the bean is a JDK proxy generated from the interface. The annotations on the interface are Spring MVC's own
,@GetMapping ,@PostMapping and@PathVariable , the same ones a controller uses.@RequestBody andGET book sent the request, and the JSON answer became anPOST pen record through Spring's message converters.Item- Six calls were split three and three between the two instances. Without a
, theurlname is a service name, and Spring Cloud LoadBalancer chose an instance for every call, round-robin. The instances came from a fixed list ininventory ; with a registry such as Eureka, they would come from there instead, with no change to the client.spring.cloud.discovery.client.simple.instances - The 404 became
, a Feign type, with the status available throughFeignException.NotFound . The HTTP service clients above throw Spring'sstatus() types instead, so error handling code changes in a migration.HttpClientErrorException - The slow call failed after the 500 ms read timeout set for this client by name, with
. Despite its name, Spring Cloud OpenFeign does not retry by default: its defaultRetryableException never retries, so the exception reached the caller at once.Retryer
Settings go under spring.cloud.openfeign.client.configdefault
spring:
cloud:
openfeign:
client:
config:
default: # every Feign client
connect-timeout: 2000
read-timeout: 5000
logger-level: basic
inventory: # one client, by its name
read-timeout: 1000
circuitbreaker:
enabled: true # needed for fallback to be used
Feign clients often declare a fallback for when the service fails. That needs Spring Cloud CircuitBreaker, which this page's classpath does not include, so this part was not run:
@FeignClient(name = "inventory", fallback = InventoryFallback.class)
public interface InventoryFeignClient {
@GetMapping("/items/{sku}")
Item get(@PathVariable("sku") String sku);
}
@Component
class InventoryFallback implements InventoryFeignClient {
public Item get(String sku) {
return new Item(sku, 0, "fallback"); // assume out of stock
}
}
- A
takes effect only with Spring Cloud CircuitBreaker on the classpath andfallback . Aspring.cloud.openfeign.circuitbreaker.enabled=true receives the exception that caused the fallback.fallbackFactory - The fallback catches every failure, including a 404 for an item that does not exist, which then looks like "out of stock". Use a
and check the exception when the difference matters.fallbackFactory - Spring Cloud CircuitBreaker is left off this page's classpath for a reason. In a trial run with
added, Spring Cloud 2025.1 also wrapped the HTTP service client group of the first program in a circuit breaker, and its 404 forspring-cloud-starter-circuitbreaker-resilience4j arrived aslamp , with theNoFallbackAvailableException exception only as its cause. Check your error handling when you add the circuit breaker starter to an application that uses HTTP service clients.NotFound - Feign has its own
,ErrorDecoder andRequestInterceptor types, configured per client by bean or property. The logger levelsRetryer ,BASIC andHEADERS only print when the client's logger is set toFULL .DEBUG - Spring Cloud OpenFeign 4 and later support Apache HttpClient 5, not HttpClient 4, as the underlying client.
Migrating from Feign to HTTP service clients
Most Feign interfaces translate line by line. The method signatures stay; the annotations change:
| OpenFeign | HTTP service client |
|---|---|
@EnableFeignClients | @ImportHttpServices |
@FeignClient(name = "inventory", url = ...) | Group inventoryspring.http.serviceclient.inventory.base-url |
@GetMapping@PostMapping | @GetExchange@PostExchange |
@RequestMapping | @HttpExchange |
@PathVariable@RequestParam@RequestHeader@RequestBody | The same annotations |
spring.cloud.openfeign.client.config.*.read-timeout | spring.http.serviceclient.*.read-timeout |
RequestInterceptor | RestClient |
ErrorDecoder | defaultStatusHandler |
fallbackfallbackFactory | A wrapping service with @Retryable |
Load balancing by service name also carries over. Instead of Feign's built-in integration, give the client a RestClient.Builder@LoadBalanced
@Bean
@LoadBalanced
RestClient.Builder loadBalancedBuilder() {
return RestClient.builder();
}
@Bean
InventoryClient inventoryClient(@LoadBalanced RestClient.Builder builder) {
RestClient rest = builder.baseUrl("http://inventory").build(); // a service name
return HttpServiceProxyFactory.builderFor(RestClientAdapter.create(rest)).build()
.createClient(InventoryClient.class);
}
The load balancer resolves inventory
Traps with declarative clients
- Missing parameter names:
without a name needs the@PathVariable String sku compiler flag, which the Spring Boot Maven and Gradle plugins set. Without it, the first call fails with "Name for argument of type [java.lang.String] not specified". Give the names explicitly, as in-parameters , in libraries built without the plugins.@PathVariable("sku") - Hidden remote calls: a method call that looks local can take seconds or fail. Name client interfaces clearly, keep them at the edge of the service, and never call them inside a database transaction.
- Error bodies lost: the default exceptions keep the response body, but code that catches only the type loses useful detail. Map important statuses to domain exceptions in one place, as the group configurer does.
- No timeout: as shown above, set read and connect timeouts on every group.
- Shared DTOs: sharing request and response classes between the two services in a library couples their release cycles. A small copy of the fields the client needs is often the better trade-off.
Choosing a client
| Situation | Choice |
|---|---|
| New code on Spring Boot 4 | HTTP service clients with @ImportHttpServices |
| Spring Boot 3, or no Spring Boot | HTTP interfaces with HttpServiceProxyFactory |
| Existing OpenFeign clients that work | Keep them, and migrate when they need changes |
| Reactive application | HTTP interfaces on WebClientMonoFlux |
| One-off or highly dynamic requests | RestClient |
| Calls by service name through a registry | A @LoadBalancedRestClient.Builder |
Declarative clients make remote calls short to write, which is exactly why their timeouts, error handling and retries deserve deliberate configuration. For calling services through an API gateway instead, see the