用途
该技能用于在 Spring Boot 3 / Spring Framework 6 中,以声明式 @HttpExchange 接口的方式调用外部 HTTP API。Spring Framework 6 支持 @HttpExchange 接口,但 Boot 3 不提供 Boot 4 的 @ImportHttpServices 分组自动注册功能,因此需要显式构建客户端适配器。
主要能力
- 定义声明式 HTTP 客户端接口,例如:
@HttpExchange("/orders")
interface OrderApiClient {
@GetExchange("/{id}")
OrderDto get(@PathVariable UUID id);
}
- 通过配置类手动注册生成的代理 Bean:
@Configuration
class ClientConfig {
@Bean
OrderApiClient orderApiClient(RestClient.Builder builder,
@Value("${clients.orders.base-url}") String baseUrl) {
RestClient client = builder.baseUrl(baseUrl).build();
HttpServiceProxyFactory factory =
HttpServiceProxyFactory.builderFor(RestClientAdapter.create(client)).build();
return factory.createClient(OrderApiClient.class);
}
}
- 对返回 Mono 或 Flux 的响应式接口,使用 WebClientAdapter。
- 在客户端适配层配置基础 URL、超时、认证与错误转换,而不是放在控制器或领域服务中。
- 建议每个外部服务使用一个工厂/配置器。
使用方式
按照上述模式定义接口并显式注册代理 Bean;响应式返回类型改用 WebClientAdapter;将基础 URL 等配置放入配置文件,通过 @Value 注入。
适用场景
适用于 Spring Boot 3 项目中需要以声明式方式调用外部 HTTP API 的场景,尤其是希望将客户端配置与领域逻辑分离、统一处理认证与错误转换的项目。
限制与常见陷阱
- 不要使用 @ImportHttpServices,该 Boot 4 注册 API 在 Boot 3 中不可用。
- 不要给接口添加 @Component 或实现类,应将生成的代理注册为 Bean。
- 对 Mono 或 Flux 返回类型不要使用 RestClient,应使用 WebClientAdapter。
- 不要在注解中硬编码远程主机,URL 应保留在配置中。
- 不要让传输错误泄漏到领域层,应在客户端适配器中转换。
- 不要为每个请求创建新客户端,应配置并复用单例代理。