Backend Development 22 min read

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

The article introduces retrofit-spring-boot-starter, a lightweight HTTP client library for Spring Boot that simplifies HTTP calls, offers extensive features such as custom OkHttpClient injection, annotation‑based interceptors, retry, logging, circuit‑breaker, and provides detailed usage examples, configuration options, and advanced customization techniques.

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

In SpringBoot projects, using okhttp , httpClient or RestTemplate directly for HTTP requests is cumbersome and hard to manage uniformly. This article recommends retrofit‑spring‑boot‑starter , a lightweight HTTP client framework that integrates Retrofit with SpringBoot, providing many enhancements and currently at version 2.2.2 .

Preface

Retrofit is a type‑safe HTTP client for Android and Java that supports interface‑based request definitions. Since Retrofit does not officially support SpringBoot integration, retrofit‑spring‑boot‑starter was created to bridge the gap.

The starter quickly integrates Retrofit into SpringBoot and adds numerous features, dramatically simplifying development.

Features

Custom OkHttpClient injection

Annotation‑based interceptors

Connection pool management

Logging

Request retry

Error decoder

Global interceptors

Circuit‑breaker (Sentinel)

Microservice HTTP calls

Call adapters

Data converters

Quick Start

Dependency

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

Define HTTP Interface

The interface must be annotated with @RetrofitClient . Example:

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

Inject and Use

@Service
public class TestService {
    @Autowired
    private HttpApi httpApi;
    public void test() {
        // invoke HTTP request via httpApi
    }
}

HTTP Request Annotations

All request annotations are the native Retrofit ones. See the table below for supported annotations.

Annotation Category

Supported Annotations

Request Method

@GET
@HEAD
@POST
@PUT
@DELETE
@OPTIONS

Headers

@Header
@HeaderMap
@Headers

Query Params

@Query
@QueryMap
@QueryName

Path Params

@Path

Form‑encoded

@Field
@FieldMap
@FormUrlEncoded

Multipart

@Multipart
@Part
@PartMap

URL

@Url

Configuration Items

The starter provides many configurable properties. Example application.yml 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

Advanced Features

Custom OkHttpClient Injection

Define a static method returning OkHttpClient.Builder and annotate it with @OkHttpClientBuilder :

@RetrofitClient(baseUrl = "http://ke.com")
public interface HttpApi3 {
    @OkHttpClientBuilder
    static OkHttpClient.Builder okhttpClientBuilder() {
        return new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .readTimeout(1, TimeUnit.SECONDS)
                .writeTimeout(1, TimeUnit.SECONDS);
    }
    @GET("person")
    Result<Person> getPerson(@Url String url, @Query("id") Long id);
}

Annotation‑Based Interceptor

Implement BasePathMatchInterceptor and annotate the interface with @Intercept to apply URL‑pattern matching interception.

@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);
    }
}
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Intercept(handler = TimeStampInterceptor.class, include = {"/api/**"}, exclude = "/api/test/savePerson")
public interface HttpApi {
    @GET("person")
    Result<Person> getPerson(@Query("id") Long id);
    @POST("savePerson")
    Result<Person> savePerson(@Body Person person);
}

Custom Annotation Example (@Sign)

Define a custom annotation marked with @InterceptMark and implement a corresponding interceptor to add signature headers.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@InterceptMark
public @interface Sign {
    String accessKeyId();
    String accessKeySecret();
    String[] include() default {"/**"};
    String[] exclude() default {};
    Class
handler() default SignInterceptor.class;
}
@Component
public class SignInterceptor extends BasePathMatchInterceptor {
    private String accessKeyId;
    private String accessKeySecret;
    public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; }
    public void setAccessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; }
    @Override
    public Response doIntercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request newReq = request.newBuilder()
                .addHeader("accessKeyId", accessKeyId)
                .addHeader("accessKeySecret", accessKeySecret)
                .build();
        return chain.proceed(newReq);
    }
}
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Sign(accessKeyId = "${test.accessKeyId}", accessKeySecret = "${test.accessKeySecret}", exclude = {"/api/test/person"})
public interface HttpApi {
    @GET("person")
    Result<Person> getPerson(@Query("id") Long id);
    @POST("savePerson")
    Result<Person> savePerson(@Body Person person);
}

Circuit‑Breaker (Sentinel)

Enable degradation with the following configuration:

retrofit:
  enable-degrade: true
  degrade-type: sentinel
  resource-name-parser: com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser

Optionally configure @Degrade on interfaces or methods, or provide fallback / fallbackFactory implementations.

Call Adapters and Data Converters

The starter ships with BodyCallAdapterFactory and ResponseCallAdapterFactory , automatically selecting the appropriate adapter based on method return type (e.g., Call<T> , CompletableFuture<T> , Void , Response<T> , or any POJO).

Global converter factories can be set, defaulting to JacksonConverterFactory . Other supported converters include Gson, Moshi, Protobuf, etc.

Conclusion

retrofit‑spring‑boot‑starter is a lightweight HTTP client framework for SpringBoot that has been stable in production for over two years and is adopted by multiple external companies.

JavamicroservicesconfigurationSpringBootRetrofitHTTP Client
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

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.