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") becomes GET /items/book, and the JSON response becomes the method's return value.

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 RestClient or WebClient. In the Spring Cloud 2022.0 release, the Spring Cloud team declared OpenFeign feature-complete: it gets bug fixes, but no new features, and its documentation recommends migrating to the HTTP service clients. Spring Framework 7 and Spring Boot 4 then made those clients easy to configure in groups.

Declarative HTTP clients in Spring
ClientSinceAnnotationsStatus
Spring Cloud OpenFeignIts own project since Spring Cloud Finchley (2018)@FeignClient with Spring MVC annotationsFeature-complete since 2022.0, bug fixes only
HTTP interface with HttpServiceProxyFactorySpring Framework 6.0@HttpExchange, @GetExchange, ...Current
HTTP service client groups, @ImportHttpServicesSpring Framework 7.0, Spring Boot 4.0Same, plus configuration properties per groupCurrent, 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-webmvc, spring-boot-starter-restclient, spring-cloud-starter-openfeign and spring-cloud-starter-loadbalancer for every program.

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:

Java
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;
    }
}
Output
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
  • @ImportHttpServices(group = "inventory", types = InventoryClient.class) registered a bean for the interface, and the bean is a JDK dynamic proxy. No implementation class exists in the code.
  • The property spring.http.serviceclient.inventory.base-url gave the group its address. Every interface in the group shares that RestClient configuration.
  • get("book") sent GET /items/book: the type-level @HttpExchange("/items") and the method's @GetExchange("/{sku}") were joined, and @PathVariable filled in the placeholder. The JSON came back as an Item record.
  • add returned a ResponseEntity, so the caller saw the status, 201, as well as the body. A method that returns the body type alone gets only the body.
  • search(10) sent minStock=10 as a query parameter and returned only pen, the item with at least 10 in stock.
  • For the missing lamp, the 404 became HttpClientErrorException.NotFound, the same exception RestClient throws for any 4xx response.

The method annotations reuse Spring MVC's @PathVariable, @RequestParam, @RequestHeader and @RequestBody, so the client interface reads like the controller it calls. The two applications in this program are configured with @SpringBootConfiguration, @EnableAutoConfiguration and @Import instead of @SpringBootApplication, only because both live in one source file and component scanning would otherwise give each the other's controller.

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 group, partly with properties and partly in code, against a service with a slow endpoint, a busy endpoint and one that echoes headers:

Java
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;
    }
}
Output
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
  • whoami() shows both headers arriving: X-Tenant: shop-eu from the default-header property, and Bearer token-123 from the request interceptor added by the RestClientHttpServiceGroupConfigurer.
  • The 404 for lamp became the application's own ItemNotFoundException, because the group's defaultStatusHandler claimed status 404. The caller can catch a domain exception instead of an HTTP one.
  • The 503 kept the default mapping, HttpServerErrorException.ServiceUnavailable, a subclass of HttpServerErrorException. That is the exception to configure a retry for, as on the resilience page.
  • slow() gave up after about 500 ms, the group's read-timeout, although the server needed 1.5 seconds. The client raised ResourceAccessException, caused by HttpTimeoutException from the JDK's HttpClient, which Spring Boot uses when no other HTTP client library is on the classpath.

Without a read-timeout, a call to a service that stops answering can wait for a very long time, holding a request thread all the while. Set one on every group, with spring.http.serviceclient.<group>.read-timeout and connect-timeout, or for all clients at once with spring.http.clients.read-timeout. Spring Boot 4 renamed the older spring.http.client.* properties to spring.http.clients.*; the old names still work but are deprecated.

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. Here the remote service is the JDK's built-in HTTP server, and the proxy is created by hand:

Java
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);
        }
    }
}
Output
hello ana
hello ben
  • RestClientAdapter connects the proxy factory to a RestClient, which does the HTTP work; WebClientAdapter does the same for WebClient, for interfaces that return Mono or Flux.
  • createClient produced the proxy, and both calls went to the server and returned its text.

Before Spring Framework 7, every client was declared this way, as a @Bean method per interface. @ImportHttpServices removes that boilerplate, and the group properties replace the per-client RestClient setup.

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-openfeign dependency, an enabling annotation and an interface per client. This program starts the same inventory service twice, as inventory-1 and inventory-2, and calls it through a @FeignClient that names the service but has no URL:

Java
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");
    }
}
Output
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, @PathVariable and @RequestBody, the same ones a controller uses.
  • GET book and POST pen sent the request, and the JSON answer became an Item record through Spring's message converters.
  • Six calls were split three and three between the two instances. Without a url, the name inventory is a service name, and Spring Cloud LoadBalancer chose an instance for every call, round-robin. The instances came from a fixed list in spring.cloud.discovery.client.simple.instances; with a registry such as Eureka, they would come from there instead, with no change to the client.
  • The 404 became FeignException.NotFound, a Feign type, with the status available through status(). The HTTP service clients above throw Spring's HttpClientErrorException types instead, so error handling code changes in a migration.
  • The slow call failed after the 500 ms read timeout set for this client by name, with RetryableException. Despite its name, Spring Cloud OpenFeign does not retry by default: its default Retryer never retries, so the exception reached the caller at once.

Settings go under spring.cloud.openfeign.client.config, for all clients with default or for one client by its name:

YAML
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:

Java
@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 fallback takes effect only with Spring Cloud CircuitBreaker on the classpath and spring.cloud.openfeign.circuitbreaker.enabled=true. A fallbackFactory receives the exception that caused the fallback.
  • The fallback catches every failure, including a 404 for an item that does not exist, which then looks like "out of stock". Use a fallbackFactory and check the exception when the difference matters.
  • Spring Cloud CircuitBreaker is left off this page's classpath for a reason. In a trial run with spring-cloud-starter-circuitbreaker-resilience4j added, Spring Cloud 2025.1 also wrapped the HTTP service client group of the first program in a circuit breaker, and its 404 for lamp arrived as NoFallbackAvailableException, with the NotFound exception only as its cause. Check your error handling when you add the circuit breaker starter to an application that uses HTTP service clients.
  • Feign has its own ErrorDecoder, RequestInterceptor and Retryer types, configured per client by bean or property. The logger levels BASIC, HEADERS and FULL only print when the client's logger is set to 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 constructs and their HTTP service client equivalents
OpenFeignHTTP service client
@EnableFeignClients@ImportHttpServices, per group
@FeignClient(name = "inventory", url = ...)Group inventory with spring.http.serviceclient.inventory.base-url
@GetMapping, @PostMapping on the interface@GetExchange, @PostExchange
@RequestMapping on the interface@HttpExchange on the interface
@PathVariable, @RequestParam, @RequestHeader, @RequestBodyThe same annotations
spring.cloud.openfeign.client.config.*.read-timeoutspring.http.serviceclient.*.read-timeout
RequestInterceptorRestClient request interceptor, in a group configurer
ErrorDecoderdefaultStatusHandler, in a group configurer
fallback, fallbackFactoryA wrapping service with @Retryable or a Resilience4j circuit breaker

Load balancing by service name also carries over. Instead of Feign's built-in integration, give the client a RestClient.Builder annotated with @LoadBalanced, from Spring Cloud LoadBalancer, and use the service name as the host:

Java
@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 to an instance from the service registry, such as Eureka, as the Eureka page shows.

Traps with declarative clients

  • Missing parameter names: @PathVariable String sku without a name needs the -parameters 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 @PathVariable("sku"), in libraries built without the plugins.
  • 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

HTTP client choices for calling other services
SituationChoice
New code on Spring Boot 4HTTP service clients with @ImportHttpServices and group properties
Spring Boot 3, or no Spring BootHTTP interfaces with HttpServiceProxyFactory
Existing OpenFeign clients that workKeep them, and migrate when they need changes
Reactive applicationHTTP interfaces on WebClient, with Mono and Flux return types
One-off or highly dynamic requestsRestClient directly
Calls by service name through a registryA @LoadBalanced RestClient.Builder under the client

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 Spring Cloud Gateway page; for following a request across services, see distributed tracing.