Supercharge Spring Boot HTTP Calls with Retrofit: A Complete Guide
This article introduces retrofit‑spring‑boot‑starter, a lightweight HTTP client for Spring Boot that simplifies request creation and offers powerful features such as custom OkHttpClient injection, annotation‑based interceptors, connection‑pool management, logging, retry, error decoding, circuit‑breaker support, service discovery, and flexible call adapters and converters, all with concise configuration examples.
Overview
Retrofit‑spring‑boot‑starter provides a lightweight HTTP client for Spring Boot projects, allowing developers to replace manual OkHttpClient, HttpClient or RestTemplate calls with a unified, easy‑to‑use interface. It integrates the popular Retrofit library into Spring Boot, offering many advanced features out of the box.
Quick Start
Dependency
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>Define an HTTP Interface
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
@POST("savePerson")
Result<Person> savePerson(@Body Person person);
}Inject and Use the Interface
@Service
public class TestService {
@Autowired
private HttpApi httpApi;
public void test() {
// call the remote API directly
Result<Person> result = httpApi.getPerson(1L);
}
}Key Features
Custom OkHttpClient Injection – Define a bean that returns an OkHttpClient or OkHttpClient.Builder and reference it with @OkHttpClientBuilder in the interface.
Annotation‑Based Interceptors – Use @Intercept to apply a custom interceptor to specific URL patterns, with support for include/exclude rules.
Advanced Interceptor Examples
Timestamp interceptor that adds a timestamp query parameter.
Signature interceptor that injects accessKeyId and accessKeySecret headers.
Connection‑Pool Management – Configure multiple pools in application.yml and select a pool per interface via poolName.
Logging – Enable request/response logging globally or per interface with enableLog, logLevel (ERROR, WARN, INFO, DEBUG, TRACE) and logStrategy (NONE, BASIC, HEADERS, BODY).
Retry – Add @Retry to automatically retry failed requests. Configure maxRetries, intervalMs and retry rules such as RESPONSE_STATUS_NOT_2XX, OCCUR_IO_EXCEPTION, OCCUR_EXCEPTION.
Error Decoder – Implement ErrorDecoder to translate HTTP errors or I/O exceptions into custom exceptions.
Global Interceptors – Implement BaseGlobalInterceptor or NetworkInterceptor as Spring beans to apply logic to all requests (e.g., add a source header).
Circuit Breaker (Sentinel)
Enable with enable-degrade=true and degrade-type=sentinel.
Configure degradation rules via @Degrade (count, timeWindow, strategy).
Provide fallback or fallbackFactory to return custom responses when a circuit is open.
Microservice HTTP Calls – Register a ServiceInstanceChooser (e.g., SpringCloudServiceInstanceChooser) as a Spring bean and use @Retrofit(serviceId = "my-service", path = "/api") to call other services.
Call Adapters BodyCallAdapterFactory (default) – Synchronously returns the response body as the method return type or a CompletableFuture<T>. ResponseCallAdapterFactory – Returns a Retrofit.Response<T> object.
Other return types such as Call<T>, Void, or any POJO are supported.
Converters
Jackson (default) – Configurable via spring.jackson.* properties.
Other supported factories: Gson, Moshi, Protobuf, Wire, Simple XML, JAXB.
Global converters can be set with retrofit.global-converter-factories and per‑interface with @RetrofitClient(converterFactories = {...}).
Configuration Examples (application.yml)
retrofit:
enable-response-call-adapter: true
enable-log: true
log-level: INFO
log-strategy: BASIC
enable-retry: true
retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor
enable-degrade: true
degrade-type: sentinel
resource-name-parser: com.github.lianjiatech.retrofit.spring.boot.degrade.DefaultResourceNameParser
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
retrofit:
pool:
test1:
max-idle-connections: 3
keep-alive-second: 100
test2:
max-idle-connections: 5
keep-alive-second: 50Conclusion
Retrofit‑spring‑boot‑starter turns Spring Boot into a powerful HTTP client platform with minimal configuration. By leveraging custom interceptors, connection pools, logging, retry, error decoding, circuit breaking, service discovery, and flexible call adapters and converters, developers can build robust, maintainable microservice communication with just a few annotations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
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.
