Integrating Retrofit with Spring Boot via retrofit-spring-boot-starter
This article explains how to use the retrofit‑spring‑boot‑starter library to seamlessly combine Square's Retrofit HTTP client with Spring Boot, covering dependency setup, annotation configuration, interface definition, injection, annotation‑based interceptors, connection‑pool management, logging, exception formatting, call adapters, converters, and global interceptors.
Retrofit is an open‑source Java HTTP client from Square, and retrofit‑spring‑boot‑starter provides a quick way to integrate Retrofit with the Spring Boot framework, adding several useful enhancements.
Dependency
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>Enable scanning
@SpringBootApplication
@RetrofitScan("com.github.lianjiatech.retrofit.spring.boot.test")
public class RetrofitTestApplication {
public static void main(String[] args) {
SpringApplication.run(RetrofitTestApplication.class, args);
}
}Define an HTTP interface
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
}Inject and use the interface
@Service
public class TestService {
@Autowired
private HttpApi httpApi;
public void test() {
// call httpApi methods here
}
}Annotation‑based interceptor
@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);
}
}Apply the interceptor on an interface:
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Intercept(handler = TimeStampInterceptor.class, include = {"/api/**"}, exclude = "/api/test/savePerson")
public interface HttpApi { ... }Custom interceptor annotation (@Sign)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@InterceptMark
public @interface Sign {
String accessKeyId();
String accessKeySecret();
String[] include() default {"/**"};
String[] exclude() default {};
Class<? extends BasePathMatchInterceptor> handler() default SignInterceptor.class;
}Corresponding handler:
@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);
}
}Use @Sign on an interface:
@RetrofitClient(baseUrl = "${test.baseUrl}")
@Sign(accessKeyId = "${test.accessKeyId}", accessKeySecret = "${test.accessKeySecret}", exclude = {"/api/test/person"})
public interface HttpApi { ... }Connection‑pool management
retrofit:
pool:
test1:
max-idle-connections: 3
keep-alive-second: 100
test2:
max-idle-connections: 5
keep-alive-second: 50Specify the pool on a client:
@RetrofitClient(baseUrl = "${test.baseUrl}", poolName = "test1")
public interface HttpApi { ... }Logging
Supported log levels: ERROR, WARN, INFO, DEBUG, TRACE (default INFO). Supported strategies: NONE, BASIC, HEADERS, BODY (default BASIC). The starter uses DefaultLoggingInterceptor which delegates to OkHttp's HttpLoggingInterceptor. Custom logging interceptors can be created by extending BaseLoggingInterceptor and configuring them via retrofit.logging-interceptor.
retrofit:
logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptorHTTP exception formatter
retrofit:
http-exception-message-formatter: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultHttpExceptionMessageFormatterCall adapters
Two factories are provided:
BodyCallAdapterFactory (default, can be disabled via retrofit.enable-body-call-adapter=false) – adapts the response body to the method’s return type.
ResponseCallAdapterFactory (default, can be disabled via retrofit.enable-response-call-adapter=false) – adapts to Retrofit.Response<T>.
Supported return types include Call<T>, CompletableFuture<T>, Void, Response<T>, and any other Java type.
Example signatures:
@GET("person")
Call<Result<Person>> getPersonCall(@Query("id") Long id);
@GET("person")
CompletableFuture<Result<Person>> getPersonCompletableFuture(@Query("id") Long id);
@GET("person")
Void getPersonVoid(@Query("id") Long id);
@GET("person")
Response<Result<Person>> getPersonResponse(@Query("id") Long id);
@GET("person")
Result<Person> getPerson(@Query("id") Long id);Converters
The starter uses Jackson by default. Other converters (Gson, Moshi, Protobuf, etc.) can be added by including the corresponding dependency and registering the factory as a Spring bean.
Custom converters are created by extending Converter.Factory and configuring them as beans.
Global interceptor
@Component
public class SourceInterceptor extends BaseGlobalInterceptor {
@Override
public Response doIntercept(Chain chain) throws IOException {
Request request = chain.request();
Request newReq = request.newBuilder()
.addHeader("source", "test")
.build();
return chain.proceed(newReq);
}
}Conclusion
The retrofit‑spring‑boot‑starter offers a concise, annotation‑driven approach to perform HTTP calls in Spring Boot applications, supporting interceptors, custom logging, connection‑pool selection, call‑adapter adaptation, and flexible converters.
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.
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.
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.
