Retrofit Spring Boot Starter – A Lightweight HTTP Client Integration for Spring Boot
The article introduces retrofit‑spring‑boot‑starter, a lightweight HTTP client framework for Spring Boot that simplifies HTTP request management by integrating Retrofit with features such as custom OkHttpClient injection, annotation‑driven interfaces, global and path‑based interceptors, retry logic, logging, circuit‑breaker support, connection‑pool configuration, and flexible call‑adapter and converter factories.
Introduction
Spring Boot projects often use OkHttp, HttpClient, or RestTemplate directly, which leads to scattered and hard‑to‑manage HTTP calls. retrofit-spring-boot-starter provides a unified, annotation‑driven solution that integrates Retrofit into Spring Boot with many enhancements.
Key Features
Custom OkHttpClient injection
Annotation‑based interceptors
Connection‑pool management
Logging with configurable levels and strategies
Automatic request retry
Error decoder
Global interceptors
Circuit‑breaker (Sentinel) support
Micro‑service HTTP calls
Call adapters and data converters
Quick Start
Add the starter dependency:
com.github.lianjiatech
retrofit-spring-boot-starter
2.2.2Define a Retrofit interface:
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {
@GET("person")
Result
getPerson(@Query("id") Long id);
}Inject and use it in a service:
@Service
public class TestService {
@Autowired
private HttpApi httpApi;
public void test() {
// call httpApi methods
}
}Annotations and Interceptors
Use @RetrofitClient to bind an interface to a base URL. Interceptors can be added by implementing BasePathMatchInterceptor and annotating the interface with @Intercept :
@Component
public class TimeStampInterceptor extends BasePathMatchInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl newUrl = request.url().newBuilder()
.addQueryParameter("timestamp", String.valueOf(System.currentTimeMillis()))
.build();
Request newRequest = request.newBuilder().url(newUrl).build();
return chain.proceed(newRequest);
}
} @RetrofitClient(baseUrl = "${test.baseUrl}")
@Intercept(handler = TimeStampInterceptor.class, include = {"/api/**"}, exclude = "/api/test/savePerson")
public interface HttpApi { ... }Custom interceptor annotations can be created with @InterceptMark and linked to a handler class.
Retry, Logging, and Error Decoding
Enable automatic retries with @Retry and configure maxRetries , intervalMs , and retryRules . Logging is controlled globally via retrofit.enable-log and per‑interface with enableLog , logLevel , and logStrategy . The default logging interceptor is DefaultLoggingInterceptor .
Error decoding is handled by implementing ErrorDecoder and specifying it in @RetrofitClient(errorDecoder = MyErrorDecoder.class) .
Circuit‑Breaker (Degrade) Support
Enable Sentinel‑based circuit breaking by setting:
retrofit:
enable-degrade: true
degrade-type: sentinel
resource-name-parser: com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParserConfigure fallback or fallbackFactory on @RetrofitClient to provide custom responses when a circuit is open.
Connection‑Pool Management
Define multiple pools in application.yml and select a pool per client with the poolName attribute:
retrofit:
pool:
test1:
max-idle-connections: 3
keep-alive-second: 100
test2:
max-idle-connections: 5
keep-alive-second: 50 @RetrofitClient(baseUrl = "${test.baseUrl}", poolName = "test1")
public interface HttpApi { ... }Global Interceptors
Implement BaseGlobalInterceptor (or NetworkInterceptor ) as a Spring bean to apply logic to all HTTP requests, e.g., adding a source header:
@Component
public class SourceInterceptor extends BaseGlobalInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request newReq = chain.request().newBuilder()
.addHeader("source", "test")
.build();
return chain.proceed(newReq);
}
}Call Adapters and Converters
The starter provides two global call‑adapter factories: BodyCallAdapterFactory (default) and ResponseCallAdapterFactory . They enable return types such as Call<T> , CompletableFuture<T> , Void , Response<T> , and any POJO.
Data conversion is handled by Retrofit converters. The default is JacksonConverterFactory , but others (Gson, Moshi, Protobuf, etc.) can be added via retrofit.global-converter-factories or the converterFactories() attribute on @RetrofitClient .
Micro‑service Calls
For Spring Cloud environments, implement ServiceInstanceChooser (e.g., SpringCloudServiceInstanceChooser ) and configure it as a bean. Then use serviceId and path in @RetrofitClient to call other services.
@RetrofitClient(serviceId = "${my-service-id}", path = "/api", errorDecoder = MyErrorDecoder.class)
public interface RemoteApi { ... }Conclusion
retrofit-spring-boot-starter offers a production‑ready, lightweight HTTP client for Spring Boot, consolidating request handling, interceptors, retries, logging, circuit breaking, and conversion mechanisms into a single, easy‑to‑configure library.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.