Backend Development 21 min read

retrofit-spring-boot-starter: A Lightweight HTTP Client Framework for Spring Boot

The article introduces retrofit-spring-boot-starter, a Spring Boot‑compatible lightweight HTTP client library that integrates Retrofit with extensive features such as custom OkHttpClient injection, annotation‑driven interceptors, logging, retry, error decoding, circuit‑breaker support, connection‑pool management, call adapters and data converters, providing a concise way to perform HTTP calls in Java backend projects.

Top Architect
Top Architect
Top Architect
retrofit-spring-boot-starter: A Lightweight HTTP Client Framework for Spring Boot

retrofit-spring-boot-starter is a lightweight HTTP client framework designed for Spring Boot projects, wrapping Retrofit to offer a type‑safe, annotation‑driven way of invoking HTTP services without the boilerplate of OkHttpClient or RestTemplate.

Key features include custom OkHttpClient injection, annotation‑based interceptors, connection‑pool management, flexible logging, automatic retry, error decoding, circuit‑breaker (Sentinel) support, global interceptors, and extensible call adapters and converters.

Quick start – add the Maven dependency:

<dependency>
    <groupId>com.github.lianjiatech</groupId>
    <artifactId>retrofit-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

Define an HTTP interface using the @RetrofitClient annotation. The interface must be marked with @RetrofitClient and can use any Retrofit request annotations such as @GET , @POST , @Query , @Body , etc.

@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {
    @GET("person")
    Result
getPerson(@Query("id") Long id);

    @POST("savePerson")
    Result
savePerson(@Body Person person);
}

The library also provides a table of supported HTTP request annotations (e.g., @GET , @POST , @Header , @QueryMap , @Multipart , etc.) that can be used directly in the interface.

Configuration can be done via application.yml (or application.properties ). Example snippet:

retrofit:
  enable-response-call-adapter: true
  enable-log: true
  pool:
    test1:
      max-idle-connections: 3
      keep-alive-second: 100
    test2:
      max-idle-connections: 5
      keep-alive-second: 50
  disable-void-return-type: false
  retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor
  global-converter-factories:
    - retrofit2.converter.jackson.JacksonConverterFactory
  global-call-adapter-factories:
    - com.github.lianjiatech.retrofit.spring.boot.core.BodyCallAdapterFactory
    - com.github.lianjiatech.retrofit.spring.boot.core.ResponseCallAdapterFactory
  enable-degrade: true
  degrade-type: sentinel
  resource-name-parser: com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser

Annotation‑based interceptors allow you to apply custom logic to specific URL patterns. Implement BasePathMatchInterceptor and annotate the interface with @Intercept(handler = YourInterceptor.class, include = {"/api/**"}, exclude = {"/api/test/savePerson"}) . A sample timestamp interceptor is shown below:

@Component
public class TimeStampInterceptor extends BasePathMatchInterceptor {
    @Override
    public Response doIntercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.url();
        long timestamp = System.currentTimeMillis();
        HttpUrl newUrl = url.newBuilder()
            .addQueryParameter("timestamp", String.valueOf(timestamp))
            .build();
        Request newRequest = request.newBuilder().url(newUrl).build();
        return chain.proceed(newRequest);
    }
}

Logging can be globally enabled with retrofit.enable-log or per‑client via @RetrofitClient(enableLog = true, logLevel = LogLevel.DEBUG, logStrategy = LogStrategy.BODY) . The default logger uses OkHttp’s HttpLoggingInterceptor , but you can provide a custom implementation by extending BaseLoggingInterceptor .

Retry is activated by adding @Retry(maxRetries = 3, intervalMs = 200, retryRules = {RetryRule.RESPONSE_STATUS_NOT_2XX, RetryRule.OCCUR_IO_EXCEPTION}) on an interface or method, with the underlying interceptor configurable via retrofit.retry-interceptor .

Error decoding lets you translate HTTP errors into domain exceptions. Implement the ErrorDecoder interface and reference it with @RetrofitClient(errorDecoder = YourErrorDecoder.class) .

Circuit‑breaker support (Sentinel) is optional. Enable it with retrofit.enable-degrade: true and configure fallback classes or factories via fallback / fallbackFactory on @RetrofitClient . The resource name parser can be customized for fine‑grained monitoring.

Call adapters automatically adapt the HTTP call result to various return types such as Call , CompletableFuture , Response , Void , or any POJO. The default adapters are BodyCallAdapterFactory and ResponseCallAdapterFactory , configurable via retrofit.global-call-adapter-factories .

Data converters handle request/response body serialization. By default, JacksonConverterFactory is used, but you can plug in Gson, Moshi, Protobuf, etc., via retrofit.global-converter-factories or the converterFactories() attribute on @RetrofitClient .

In summary, retrofit-spring-boot-starter provides a production‑ready, feature‑rich HTTP client for Spring Boot, simplifying service‑to‑service calls, enhancing observability, and supporting advanced patterns like circuit‑breaking and custom interceptors.

JavamicroservicesSpring BootInterceptorcircuit breakerRetrofitHTTP Client
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.