Backend Development 20 min read

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

This article presents retrofit-spring-boot-starter, a lightweight Spring Boot starter that simplifies HTTP calls by integrating Retrofit with customizable OkHttpClient, annotation‑driven interceptors, logging, retry, circuit‑breaker, error decoding, and flexible converters, along with detailed usage examples and configuration guidelines.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Introducing retrofit-spring-boot-starter: A Lightweight HTTP Client for Spring Boot

The author introduces retrofit-spring-boot-starter , a lightweight HTTP client framework designed for Spring Boot projects to replace cumbersome uses of OkHttp, HttpClient, or RestTemplate.

Key Features include custom OkHttpClient, annotation‑based interceptors, logging, retry, circuit‑breaker, error decoder, microservice HTTP calls, global interceptors, adapters, converters, and meta‑annotations.

Quick Start shows how to add the Maven dependency:

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

Define an HTTP interface annotated with @RetrofitClient and standard Retrofit annotations such as @GET , @POST , @Query , etc.

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

Inject the interface into a Spring service with @Autowired and call methods directly.

@Service
public class TestService {
    @Autowired
    private HttpApi httpApi;
    public void test() {
        // use httpApi to send HTTP requests
    }
}

Configuration properties allow global settings for converters, call adapters, logging, retry, timeout, and degradation. Example YAML/YML snippet:

retrofit:
  global-converter-factories:
    - com.github.lianjiatech.retrofit.spring.boot.core.BasicTypeConverterFactory
    - retrofit2.converter.jackson.JacksonConverterFactory
  global-log:
    enable: true
    log-level: info
    log-strategy: basic
  global-retry:
    enable: false
    interval-ms: 100
    max-retries: 2
    retry-rules:
      - response_status_not_2xx
      - occur_io_exception
  global-timeout:
    read-timeout-ms: 10000
    write-timeout-ms: 10000
    connect-timeout-ms: 10000
  degrade:
    degrade-type: none

Advanced Features cover custom OkHttpClient registration via SourceOkHttpClientRegistrar , annotation‑driven interceptors by extending BasePathMatchInterceptor , and creating custom interceptor annotations such as @Sign for dynamic header injection.

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

Logging can be configured globally or per‑method using @Logging , with strategies NONE, BASIC, HEADERS, and BODY.

Retry support includes global retry (disabled by default) and method‑level retry via @Retry , with configurable intervals, max attempts, and rules.

Circuit‑breaker (degrade) options support Sentinel and Resilience4j; enable with degrade-type=sentinel or degrade-type=resilience4j and annotate interfaces or methods with @SentinelDegrade or @Resilience4jDegrade . Fallback classes can be provided for custom error handling.

Error decoding is achieved by specifying an errorDecoder() on @RetrofitClient , allowing conversion of HTTP errors into custom exceptions.

Microservice calls can use a custom ServiceInstanceChooser to resolve service IDs to URLs, e.g., integrating with Spring Cloud LoadBalancer.

Global interceptors ( GlobalInterceptor ) and network interceptors ( NetworkInterceptor ) can be defined as Spring beans to apply cross‑cutting concerns to all HTTP requests.

The framework supports a wide range of Retrofit call adapters (synchronous, CompletableFuture, Mono, Single, etc.) and converters (Jackson, Gson, Moshi, Protobuf, etc.), configurable globally via retrofit.global-converter-factories or per‑interface via @RetrofitClient.converterFactories .

Meta‑annotations and @AliasFor enable composition of common configurations into reusable custom annotations.

Additional examples demonstrate form‑encoded parameters, file upload/download using @Multipart and @Part , dynamic URLs with @Url , and sending a request body with a DELETE request via @HTTP(method="DELETE", hasBody=true) .

The article concludes with a call‑to‑action encouraging readers to like, share, and follow the author’s knowledge community.

JavaMicroservicesloggingSpring Bootcircuit breakerRetrofitHTTP Client
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

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.