Integrating Retrofit with Spring Boot Using retrofit‑spring‑boot‑starter
This article explains how to quickly integrate the Retrofit HTTP client into a Spring Boot project with the retrofit‑spring‑boot‑starter, covering dependency setup, configuration annotations, interface definition, custom annotation‑based interceptors, connection‑pool management, logging, exception formatting, call adapters, converters, and global interceptors, all illustrated with complete code examples.
The article introduces okhttp as a Java HTTP client library and its higher‑level wrapper Retrofit, then shows how the open‑source retrofit‑spring‑boot‑starter simplifies integrating Retrofit into a Spring Boot application.
Dependency
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>Configuration
Annotate a Spring configuration class with @RetrofitScan (or place it on the main class) to enable automatic scanning of Retrofit client interfaces.
Defining an HTTP Interface
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface HttpApi {
@GET("person")
Result<Person> getPerson(@Query("id") Long id);
}Injecting and Using the Client
@Service
public class TestService {
@Autowired
private HttpApi httpApi;
public void test() {
// call httpApi methods here
}
}Annotation‑Based Interceptor
Implement a custom interceptor by extending BasePathMatchInterceptor and annotate the target interface with @Intercept to apply it to selected paths.
@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);
}
}Custom Annotation Example (@Sign)
Define a meta‑annotation @Sign that includes include(), exclude() and handler() attributes, then implement SignInterceptor 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<? extends BasePathMatchInterceptor> handler() default SignInterceptor.class;
} @Component
public class SignInterceptor extends BasePathMatchInterceptor {
private String accessKeyId;
private String accessKeySecret;
public void setAccessKeyId(String id) { this.accessKeyId = id; }
public void setAccessKeySecret(String secret) { this.accessKeySecret = secret; }
@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);
}
}Connection‑Pool Management
Configure multiple pools in application.yml and select a pool per client via the poolName attribute of @RetrofitClient.
retrofit:
pool:
test1:
max-idle-connections: 3
keep-alive-second: 100
test2:
max-idle-connections: 5
keep-alive-second: 50Logging
Set logLevel (ERROR, WARN, INFO, DEBUG, TRACE) and logStrategy (NONE, BASIC, HEADERS, BODY) on each client; the starter uses DefaultLoggingInterceptor based on OkHttp’s HttpLoggingInterceptor.
HTTP Exception Formatter
Customize error messages by providing a bean that extends BaseHttpExceptionMessageFormatter, the default being DefaultHttpExceptionMessageFormatter.
Call Adapters
The starter registers two adapters: BodyCallAdapterFactory (default, converts responses to the method’s return type) and ResponseCallAdapterFactory (returns Response<T>). It also supports Call<T>, CompletableFuture<T>, Void, and any other Java type.
Converters
Jackson is the default converter; other options (Gson, Moshi, Protobuf, etc.) can be added by including the appropriate dependency and registering the corresponding Converter.Factory as a Spring bean.
Global Interceptor
Implement BaseGlobalInterceptor to apply logic (e.g., adding a common header) to every HTTP request made through Retrofit.
@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);
}
}The article concludes with a call to share the tutorial and join the author’s architecture community.
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.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.
