Sub topic 6
Creating the proxy with HttpServiceProxyFactory
This chapter assumes you know Java 17 records and interfaces, basic Spring Boot (beans, @Configuration, dependency injection), HTTP basics, and the Spring MVC annotations @PathVariable and @RequestParam. You have already seen how to describe an API with @HttpExchange. Here you will turn that interface into a working object.
What the factory does
An @HttpExchange interface has no implementation. HttpServiceProxyFactory creates one at runtime. It uses a JDK dynamic proxy, which is a generated class that implements your interface and routes every method call to a handler.
When you call createClient(TodoClient.class), the factory does the following:
- It scans the interface for methods annotated with
@HttpExchangeor one of its variants, such as@GetExchangeand@PostExchange. - For each method, it builds a description of the request: the HTTP method, the URL template, and how each argument maps to a path variable, query parameter, header, or body.
- It returns a proxy. Each call on the proxy runs that description against a low-level client.
The factory does not send HTTP requests itself. It delegates to an adapter, which wraps a real HTTP client. This keeps the interface the same whether the transport is RestClient, WebClient, or RestTemplate.
The adapters
An adapter implements the HttpExchangeAdapter interface. Spring provides three. The type you choose decides which return types are allowed and how errors surface.
| Adapter | Wraps | Style | Notes |
|---|---|---|---|
| `RestClientAdapter` | `RestClient` | Blocking | The usual choice for new Spring Boot applications. |
| `WebClientAdapter` | `WebClient` | Reactive or blocking | Supports `Mono`, `Flux`, and other reactive return types. |
| `RestTemplateAdapter` | `RestTemplate` | Blocking | Useful when you already have a configured `RestTemplate`. |
RestClientAdapter and RestTemplateAdapter are blocking. A method that returns Mono<Todo> needs WebClientAdapter. The reactive case is covered in a later chapter.
Building a proxy step by step
The standard recipe has four steps. First, get a RestClient. Second, wrap it in an adapter. Third, build the factory. Fourth, ask the factory for a client.
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
public class ManualProxyExample {
public static void main(String[] args) {
RestClient restClient = RestClient.builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory =
HttpServiceProxyFactory.builderFor(adapter).build();
TodoClient client = factory.createClient(TodoClient.class);
System.out.println(client.getTodo(1));
}
}This example assumes the TodoClient interface and Todo record from the previous chapter are in the same package. It sends a real request to a public test API, so it needs network access.
The static method builderFor(adapter) was added in Spring Framework 6.1. Older tutorials use HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient)) or builder().exchangeAdapter(...). On current versions, prefer builderFor.
Where the base URL lives
The base URL belongs to the RestClient, not to the factory. The @HttpExchange path on the interface is appended to it.
With the base URL https://jsonplaceholder.typicode.com and the type-level path /todos, the call getTodo(1) on a method annotated @GetExchange("/{id}") requests https://jsonplaceholder.typicode.com/todos/1.
This separation is useful. The interface describes the shape of the API, and the RestClient describes where to reach it and how. You can point the same interface at a staging server and a production server by building two RestClient instances.
If a method needs a different host for one call, declare a URI parameter. Spring then uses that value as the full URL and ignores the base URL and annotation path.
import java.net.URI;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
@HttpExchange
public interface DynamicClient {
@GetExchange
String fetch(URI uri);
}Customizing the factory
The factory builder accepts options beyond the adapter. The three you are most likely to need are listed here.
customArgumentResolver(...)registers a resolver for your own argument types. Use it when many methods share a parameter, such as a tenant context object that must become a header.conversionService(...)replaces the service used to turn method arguments into strings for path variables, query parameters, and headers. By default Spring uses aDefaultFormattingConversionService.embeddedValueResolver(...)resolves${...}placeholders inside annotation values. Without it, a path such as@GetExchange("${api.todos.path}")is sent literally.
The placeholder case catches many people. The resolver is not set by default when you build the factory by hand. In a Spring application, wire it from the environment:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@Configuration
class PlaceholderConfig {
@Bean
TodoClient placeholderTodoClient(RestClient.Builder builder, Environment env) {
RestClient restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.embeddedValueResolver(env::resolvePlaceholders)
.build();
return factory.createClient(TodoClient.class);
}
}The method reference env::resolvePlaceholders is lenient. It leaves an unknown placeholder untouched instead of failing. If you want startup to fail on a missing property, use env::resolveRequiredPlaceholders.
Using the Boot-provided builder
Spring Boot auto-configures a RestClient.Builder bean. It is a prototype-scoped bean, so each injection point receives a fresh copy. That copy already carries Boot's message converters and any RestClientCustomizer beans in your application. Inject it rather than calling RestClient.builder() when you want your Jackson settings, observability, and other global customization to apply.
Calling RestClient.builder() directly gives you a plain builder with defaults only. The proxy still works, but JSON handling may differ from the rest of your application. This is a common source of surprising serialization behavior, for example dates written in a different format.
A related point: the builder is mutable. If you share one builder instance across two clients and call baseUrl on both, the later call changes the same object. The prototype scope exists to prevent this. If you inject one builder and build two clients from it, call builder.clone() first.
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 TwoClientsConfig {
@Bean
TodoClient stagingTodoClient(RestClient.Builder builder) {
return create(builder.clone().baseUrl("https://staging.example.com").build());
}
@Bean
TodoClient productionTodoClient(RestClient.Builder builder) {
return create(builder.clone().baseUrl("https://api.example.com").build());
}
private static TodoClient create(RestClient restClient) {
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(TodoClient.class);
}
}Two beans of the same type cause an ambiguity error at injection points. Distinguish them with @Qualifier, or with the injection point's parameter name.
Behavior and limits of the proxy
Keep these points in mind when you rely on the generated object.
- Only annotated methods work. A method with no
@HttpExchangevariant fails when the factory builds the proxy. Spring throws anIllegalStateExceptionthat names the method, so the error appears at startup of that bean and not at the first call. - Default and static methods are allowed. A
defaultmethod on the interface runs as plain Java. Use it to add convenience overloads that call other exchange methods. - The proxy is thread-safe. It holds no per-call state, and the underlying
RestClientis thread-safe. Create it once and share it. toString,equals, andhashCodeare handled. They are answered by the proxy and do not trigger HTTP calls.- Validation happens early. The factory checks the argument and return types of each method when you call
createClient. An unsupported return type fails there, not on the first request.
Because the proxy is a JDK proxy, you must declare the client as an interface. A class cannot be proxied this way.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `IllegalStateException` while creating the client | A method has no exchange annotation, or has an unsupported parameter or return type | Annotate the method, or change its signature |
| `${...}` appears in the request URL | No `embeddedValueResolver` on the factory | Add `.embeddedValueResolver(env::resolvePlaceholders)` |
| `NoUniqueBeanDefinitionException` | Two client beans of the same type | Add `@Qualifier` at the bean and the injection point |
| Request goes to the wrong host | Shared builder mutated by two `baseUrl` calls | Call `builder.clone()` before customizing |
| Dates or field names serialize differently than elsewhere | The client used `RestClient.builder()` instead of the Boot builder | Inject `RestClient.Builder` |
| `ClassCastException` or conversion error on `Mono` | A reactive return type used with `RestClientAdapter` | Switch to `WebClientAdapter` |
Exercise
You build two TodoClient beans from one injected RestClient.Builder. Both beans end up calling the same host, even though you set a different baseUrl for each. What is the likely cause, and what is the fix?
Show answer
Both beans call baseUrl on the same mutable builder, so the second call overwrites the first. Because the first bean's RestClient was already built, the more likely symptom is that builds happen in an order that sees the latest value, or that the shared state leaks between them. The fix is to call builder.clone() before setting baseUrl for each client, so each RestClient is built from its own copy.
Exercise
A method on your interface is annotated with @GetExchange("${api.todos.path}"), and requests go to a URL that literally contains ${api.todos.path}. What do you change on the factory?
Show answer
Set an embedded value resolver, for example HttpServiceProxyFactory.builderFor(adapter).embeddedValueResolver(env::resolvePlaceholders).build(), where env is the Spring Environment. Without it, the factory does not resolve placeholders in annotation values.