Sub topic 7
Exposing the client as a bean
This chapter assumes you know Spring Boot basics (beans, @Configuration, constructor injection) and have read the earlier chapters on @HttpExchange interfaces and HttpServiceProxyFactory. You can already build a proxy by hand. Here you turn it into a bean that the rest of the application injects like any other dependency.
Why the proxy must be a bean
An @HttpExchange interface has no implementation class. HttpServiceProxyFactory creates one at runtime as a JDK dynamic proxy. Spring does not find that proxy through component scanning, because there is no class to scan. Annotating the interface with @Component does nothing, since Spring cannot instantiate an interface.
You have to register the proxy yourself. The usual way is a @Bean method that builds the proxy and returns it. Once registered, the bean behaves like any other, with constructor injection, @Primary, @Qualifier, and test overrides.
The diagram shows how the pieces connect at startup.
The standard @Bean method
This is the configuration from the earlier chapter, with the pieces labeled:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@Configuration
class TodoClientConfig {
@Bean
TodoClient todoClient(RestClient.Builder builder) {
RestClient restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build();
return factory.createClient(TodoClient.class);
}
}Four things happen in order:
- Spring Boot injects its auto-configured
RestClient.Builder. - You set the base URL and call
build()to get aRestClient. RestClientAdapter.create(...)wraps theRestClientso the factory can call it through a common interface.createClient(TodoClient.class)inspects the annotations on the interface and returns the proxy.
The bean type is the interface, TodoClient. Callers depend only on the interface, which also makes them easy to mock.
Why the builder is safe to configure
Boot registers RestClient.Builder with prototype scope. Every injection point gets a fresh builder, already carrying Boot's defaults such as message converters and any RestClientCustomizer beans. Calling baseUrl(...) on your copy does not change anyone else's builder. If you build the builder yourself with RestClient.builder(), you skip those Boot defaults, including the Jackson configuration you set up in application.properties.
Injecting the client
Nothing in the consuming code reveals that the implementation is generated:
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
@Service
class TodoService {
private final TodoClient todoClient;
TodoService(TodoClient todoClient) {
this.todoClient = todoClient;
}
Todo findOrNull(long id) {
try {
return todoClient.getTodo(id);
} catch (HttpClientErrorException.NotFound e) {
return null;
}
}
}Single-constructor injection needs no @Autowired. The call on todoClient is made on the proxy. The proxy resolves the annotation metadata for that method, builds the request, runs it through the RestClient, and converts the response to the return type.
Registering several clients
Real applications usually call more than one remote API. Repeating the four-step recipe for each gets noisy. A small helper keeps each bean to one line:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.annotation.HttpExchange;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@HttpExchange("/users")
interface UserClient {
@GetExchange("/{id}")
User getUser(@PathVariable long id);
}
record User(Long id, String name) {}
@Configuration
class ClientsConfig {
@Bean
TodoClient todoClient(RestClient.Builder builder) {
return create(builder, "https://jsonplaceholder.typicode.com", TodoClient.class);
}
@Bean
UserClient userClient(RestClient.Builder builder) {
return create(builder, "https://jsonplaceholder.typicode.com", UserClient.class);
}
private static <T> T create(RestClient.Builder builder, String baseUrl, Class<T> type) {
RestClient restClient = builder.baseUrl(baseUrl).build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build();
return factory.createClient(type);
}
}Each @Bean method receives its own prototype builder, so the two clients cannot overwrite each other's base URL. In a real project the two clients would usually point at different hosts, and the second argument to create would differ.
Two clients of the same type, for example one for a staging API and one for production, are ordinary same-type beans. Give the @Bean methods different names and inject with @Qualifier, or mark one @Primary.
Registering by group with @ImportHttpServices
On Spring Framework 7 and Spring Boot 4, you can skip the factory code. The @ImportHttpServices annotation registers the interface as a bean in a named group:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.service.registry.ImportHttpServices;
@Configuration
@ImportHttpServices(group = "todos", types = TodoClient.class)
class HttpClientsConfig {
}The group name connects the client to its configuration. Boot reads properties under spring.http.serviceclient.<group>:
spring.http.serviceclient.todos.base-url=https://jsonplaceholder.typicode.comThe injection site stays the same, TodoService still takes a TodoClient. A later chapter covers groups in detail, including how to share defaults and what to configure per group. For now, treat this as the replacement for the @Bean method when you are on the newer versions. If you are on Spring Boot 3.x, use the manual @Bean approach, because @ImportHttpServices is not available there.
| Approach | Needs | You write | Configuration lives in |
|---|---|---|---|
| `@Bean` with `HttpServiceProxyFactory` | Spring Framework 6.1+ | Factory code per client or helper | Java code |
| `@ImportHttpServices` | Spring Framework 7 and Boot 4 | One annotation | Properties, plus optional customizers |
Common errors
NoSuchBeanDefinitionExceptionfor the interface. The interface was never registered. Check that your@Beanmethod or@ImportHttpServicesis in a configuration class that component scanning reaches.- Annotating the interface with
@Componentor@Service. This has no effect. Spring cannot instantiate an interface, so the bean never appears. - Wrong base URL when paths are combined. The type-level
@HttpExchangepath is prefixed to each method path, and the result is resolved against the base URL. A base URL with a path segment, such ashttps://host/api, and a type-level path of/todosgivehttps://host/api/todos. Test the final URL, as the testing chapter shows. - Building the builder by hand.
RestClient.builder()ignores Boot's customizers. InjectRestClient.Builderunless you have a reason not to. - Passing an unannotated interface. The factory only handles methods that carry an exchange annotation. A method without one will not make a request. Default methods on the interface run as normal Java code.
- Sharing one
RestClientunintentionally. Reusing a builtRestClientfor a second client is fine when the base URL and defaults are meant to be shared. If they differ, build a separateRestClientfor each, as the helper above does.
Lifecycle and testing notes
The proxy is a singleton like any other bean. It holds no per-request state, and the underlying RestClient is thread-safe, so concurrent calls from many request threads are fine. Creating the proxy is cheap but not free, because the factory parses annotations when it runs. That is a reason to create each client once, as a bean, and not inside a method that runs on every request.
Because the client is a normal bean, tests can replace it. In a Spring Boot test you can supply a mock with @MockitoBean (Spring Framework 6.2 and later) and skip HTTP entirely. To check the generated requests themselves, build the proxy in the test with MockRestServiceServer, as the testing chapter shows.
Choosing between the two approaches
Use the @Bean method when you are on Spring Boot 3.2 or 3.3 and later 3.x releases, when one client needs unusual construction, or when you want the whole setup visible in Java. Use @ImportHttpServices when you are on Boot 4, when you have several clients that share settings, or when you want operators to change base URLs through properties.
The two can coexist in one application during a migration. They produce ordinary beans, and consumers cannot tell which route created them.
Exercise
A teammate adds @Service to the TodoClient interface and removes the @Bean method. The application now fails at startup with NoSuchBeanDefinitionException for TodoClient. Why, and what are two ways to fix it?
Show answer
Component scanning only registers concrete classes it can instantiate, and an interface has no implementation until HttpServiceProxyFactory creates a proxy. Restore a @Bean method that builds the proxy with RestClientAdapter and HttpServiceProxyFactory.createClient(TodoClient.class). On Spring Framework 7 and Boot 4, you can instead add @ImportHttpServices(group = "todos", types = TodoClient.class) on a configuration class and set spring.http.serviceclient.todos.base-url.
Exercise
Two @Bean methods each take a RestClient.Builder and call baseUrl(...) with different URLs. A colleague worries the second call overwrites the first client's URL. Is the worry justified?
Show answer
No. Spring Boot registers RestClient.Builder with prototype scope, so each injection point gets its own builder. Calling baseUrl on one copy does not affect the other. The worry would be justified only if you stored one builder in a field and reused it for both clients.
Exercise
You need two clients of the same interface type, one pointing at staging and one at production. How do you register them so a service can pick the right one?
Show answer
Declare two @Bean methods with different names, each building its own RestClient with a different base URL. In the consumer, inject the one you want with @Qualifier("stagingTodoClient") (using the bean's name), or mark one @Primary and qualify only the other.