Sub topic 12
Registering clients by group in Spring Framework 7 and Boot 4
This chapter assumes you can already write an @HttpExchange interface, know how HttpServiceProxyFactory and RestClientAdapter create a proxy, and can write a Spring @Configuration class. It also assumes you know what a RestClient.Builder is. It targets Spring Framework 7 and Spring Boot 4. Earlier versions do not have the annotations and properties shown here.
The problem with one factory per client
In earlier chapters you registered TodoClient with a @Bean method. That method built a RestClient, wrapped it in an adapter, created a factory, and called createClient. This works, but it is boilerplate that repeats for every interface. With five remote APIs you write five nearly identical methods. Each one hard-codes a base URL, and each one needs its own timeout and header setup.
Spring Framework 7 replaces this with groups. A group is a named set of HTTP interfaces that share one underlying client configuration. You declare which interfaces belong to which group, and Spring builds the clients and registers the proxy beans. You configure each group by name, usually in application.properties.
Declaring a group with @ImportHttpServices
Put @ImportHttpServices on a @Configuration class. The group attribute names the group. The types attribute lists the interfaces.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.service.registry.ImportHttpServices;
@Configuration
@ImportHttpServices(group = "todos", types = TodoClient.class)
class HttpClientsConfig {
}Spring registers TodoClient as a bean, so you can inject it as before:
@Service
class TodoService {
private final TodoClient todoClient;
TodoService(TodoClient todoClient) {
this.todoClient = todoClient;
}
}The @Bean method, the factory, and the adapter are gone. Spring creates the RestClient for the group and uses it to build every proxy in that group.
Registering several interfaces
You can list several types in one group, or scan a package:
@Configuration
@ImportHttpServices(group = "todos", basePackages = "com.example.todos")
@ImportHttpServices(group = "users", types = UserClient.class)
class HttpClientsConfig {
}@ImportHttpServices is repeatable, so you can stack it as shown. With basePackages, Spring scans for interfaces that declare @HttpExchange methods. Any such interface in that package joins the group. A scan is convenient, but a new interface dropped into the package silently becomes a bean in that group. Use explicit types when you want every registration to be visible in code review.
Choosing the client type
A group is backed by either a RestClient or a WebClient. Spring picks one based on what is on the classpath. In a servlet application with spring-web, it uses RestClient. If you need to force the choice, use the clientType attribute:
@ImportHttpServices(
group = "events",
types = EventClient.class,
clientType = HttpServiceGroup.ClientType.WEB_CLIENT)HttpServiceGroup is in org.springframework.web.service.registry. Use WEB_CLIENT only when the interface returns reactive types, a case the reactive chapter covers.
Configuring a group with properties
Spring Boot 4 binds properties under spring.http.serviceclient.<group> to the client of that group:
spring.http.serviceclient.todos.base-url=https://jsonplaceholder.typicode.com
spring.http.serviceclient.todos.connect-timeout=2s
spring.http.serviceclient.todos.read-timeout=5s
spring.http.serviceclient.todos.default-header.X-Client=tutorial
spring.http.serviceclient.users.base-url=https://api.example.com/v2Each group gets its own base URL, timeouts, and default headers. The todos settings do not affect users. Because the group name appears in the property key, it must match the group attribute exactly.
The properties give you the same settings you wrote by hand in the @Bean method. The base URL, default headers, and timeouts are covered in earlier chapters. This chapter only shows where they now live.
Property names to verify
The set of properties is defined by Spring Boot. Check the Boot 4 reference documentation for the exact list in your version. The base URL is the most common setting, and the timeout and header properties are the ones you are most likely to look up.
What happens at startup
Three inputs feed the group's client builder: the group definition, the properties, and any configurer beans (covered next). Spring then does what you used to do by hand. It builds one RestClient per group and one proxy per interface. All interfaces in a group share that one RestClient, and therefore share its base URL, headers, and connection settings.
Customizing in code with a group configurer
Properties cover common settings. For anything else, such as interceptors or authentication, define a configurer bean. For RestClient groups, the type is RestClientHttpServiceGroupConfigurer:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.support.RestClientHttpServiceGroupConfigurer;
@Configuration
class GroupCustomization {
@Bean
RestClientHttpServiceGroupConfigurer todosConfigurer() {
return groups -> groups
.filterByName("todos")
.forEachClient((group, builder) ->
builder.defaultHeader("X-Request-Source", "tutorial-app"));
}
}filterByName limits the callback to the named groups. Without it, the callback applies to every group. forEachClient gives you the group and its RestClient.Builder, so any builder method is available. This includes requestInterceptor, defaultStatusHandler, and requestFactory.
A common use is attaching an authentication interceptor to one group only. Credentials for one API then never get sent to another.
Mixing groups with and without properties
You can combine all three mechanisms. Order matters when they overlap. Properties and the builder customizations both modify the same RestClient.Builder. If you set the same header in a property and a configurer, avoid relying on which wins. Set each value in one place.
A practical split is:
- Put environment-specific values in properties: base URLs and timeouts differ between development and production.
- Put behavior in configurers: interceptors, status handlers, and token suppliers are code, not strings.
Testing grouped clients
@ImportHttpServices builds its own RestClient, so the MockRestServiceServer.bindTo(builder) approach from the testing chapter does not bind to it directly. You have two options:
- Test the interface without the group. Build the proxy by hand in the test, as in the earlier chapter. This verifies your annotations and argument binding, which are the parts you wrote.
- Test the wiring with a Spring Boot test. Override the group's base URL with a property that points to a local stub server, and check that the bean is injectable.
Option 1 is faster and covers most failures. Use option 2 sparingly, to catch typos in group names and properties.
Failure modes
| Symptom | Likely cause |
|---|---|
| `NoSuchBeanDefinitionException` for the client | The interface is not in `types` or the scanned package, or `@ImportHttpServices` is on a class that Spring does not process. |
| "URI is not absolute" on first call | The `base-url` property is missing, or the group name in the key does not match. |
| Header or token sent to the wrong API | A configurer has no `filterByName`. |
| Timeouts have no effect | A custom `requestFactory` in a configurer replaced the one Boot configured from the properties. |
| Wrong client type | The group is `WEB_CLIENT` but the interface returns blocking types, or the reverse. |
The timeout row deserves attention. The connect-timeout and read-timeout properties configure the request factory. If a configurer then calls requestFactory(...), it replaces that factory and the properties are lost. Set timeouts on your custom factory instead.
When to use groups
Use groups when you have more than one HTTP interface, or when you need per-environment configuration without recompiling. They also help when several interfaces call the same remote service and should share one base URL.
Keep the manual HttpServiceProxyFactory approach when you must support Spring Boot 3 or Framework 6, because groups do not exist there. It is also the better choice when a client needs construction logic that does not fit the builder callbacks, such as creating a client at runtime for each tenant.
Exercise
Your application defines @ImportHttpServices(group = "billing", types = InvoiceClient.class). Requests from InvoiceClient fail with "URI is not absolute". The properties file contains spring.http.serviceclient.invoices.base-url=https://billing.example.com. What is wrong, and how do you fix it?
Show answer
The group is named billing, but the property key uses invoices. Spring Boot applies the property to a group that does not exist, so the billing group has no base URL. Rename the key to spring.http.serviceclient.billing.base-url=https://billing.example.com, or change the group name in the annotation to match.
Exercise
You add a RestClientHttpServiceGroupConfigurer that registers an interceptor adding an Authorization header, with no call to filterByName. You have two groups, internal and partner. What is the risk, and what change removes it?
Show answer
The configurer runs for both groups, so the internal token is sent to the partner API. Add .filterByName("internal") before forEachClient, so the interceptor applies only to the internal group.