Sub topic 2
RestClient and Spring Boot's RestClient.Builder
Assume Java 17+, basic Spring Boot dependency injection, and familiarity with HTTP methods, headers, and JSON. This chapter uses Spring Framework HTTP interfaces with a synchronous RestClient.
Build the client with `RestClient.Builder`
RestClient is Spring's synchronous HTTP client. Spring Boot auto-configures a RestClient.Builder bean with the application's normal HTTP infrastructure. Configure that builder with the remote service's base URL, then build a RestClient.
@Configuration
class TodoClientConfig {
@Bean
TodoClient todoClient(
RestClient.Builder builder,
@Value("${todos.api-token}") String apiToken) {
RestClient restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.defaultHeader(HttpHeaders.AUTHORIZATION,
"Bearer " + apiToken)
.build();
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(TodoClient.class);
}
}The builder is usually the best place for settings shared by every request from this client:
baseUrlprefixes relative endpoint paths.defaultHeaderadds a header to each request.- Authentication values should come from configuration or a secret store, not source code.
Create the proxy with `HttpServiceProxyFactory`
HttpServiceProxyFactory creates a runtime implementation of an annotated interface. The RestClientAdapter connects the factory to RestClient.
@HttpExchange("/todos")
interface TodoClient {
@GetExchange("/{id}")
Todo getTodo(@PathVariable long id);
}
record Todo(Long id, Long userId, String title, boolean completed) {}For getTodo(1), the proxy sends a GET request to /todos/1. The proxy combines the type-level path with the method-level path and converts the JSON response into Todo.
Expose the client as a bean
The @Bean method registers the generated proxy in Spring's application context. Services can then inject TodoClient through a constructor, just like any other dependency.
@Service
class TodoService {
private final TodoClient client;
TodoService(TodoClient client) {
this.client = client;
}
Todo load(long id) {
return client.getTodo(id);
}
}Choose defaults and authentication carefully
A base URL keeps endpoint annotations short. Default headers are useful for an API version, correlation ID, or authorization scheme. Avoid placing long-lived tokens directly in Java files. For changing credentials, use a request interceptor or request-specific header instead of a fixed default.
Exercise
What object connects the annotated interface to the configured RestClient?
Show answer
RestClientAdapter connects them, and HttpServiceProxyFactory uses the adapter to create the interface proxy.