retrofit enables the conversion of HTTP APIs into Java interfaces. This component deeply integrates Retrofit with Spring Boot and supports various practical feature enhancements.
retrofit.global-converter-factories=com.github.lianjiatech.retrofit.spring.boot.core.jackson3.Jackson3ConverterFactory🚀 The project is continuously optimized and iterated. Contributions via ISSUES and PRs are welcome! Please consider giving a star⭐️—your support motivates our ongoing updates!
GitHub project link: https://github.com/LianjiaTech/retrofit-spring-boot-starter
Gitee project link: https://gitee.com/lianjiatech/retrofit-spring-boot-starter
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
For most Spring Boot projects, adding the dependency is sufficient. If the component fails to work after dependency injection, try the following solutions:
In some cases, RetrofitAutoConfiguration may not load properly. Attempt manual configuration import with the following code:
@Configuration
@ImportAutoConfiguration({RetrofitAutoConfiguration.class})
public class SpringBootAutoConfigBridge {
}
If the project still uses Spring XML configuration files, add the Spring Boot auto-configuration class to the XML file:
<bean class="com.yourpackage.config.SpringBootAutoConfig"/>
Interfaces must be annotated with @RetrofitClient!
@RetrofitClient(baseUrl = "http://localhost:8080/api/user/")
public interface UserService {
/**
* Query username by ID
*/
@POST("getName")
String getName(@Query("id") Long id);
}
Note: Avoid using leading slashes (
/) in method request paths. For Retrofit, ifbaseUrl = http://localhost:8080/api/test/: - A method pathpersonresults in the full URL:http://localhost:8080/api/test/person. - A method path/personresults in the full URL:http://localhost:8080/person.
Inject the interface into other Services for use!
@Service
public class BusinessService {
@Autowired
private UserService userService;
public void doBusiness() {
// Call userService methods
}
}
By default, RetrofitClient interfaces are automatically registered via Spring Boot's component scanning path. Alternatively, specify a custom scan path using @RetrofitScan on a configuration class.
HTTP request-related annotations use Retrofit's native annotations. A brief overview is provided below:
| Annotation Category | Supported Annotations |
|---|---|
| Request Methods | @GET, @HEAD, @POST, @PUT, @DELETE, @OPTIONS, @HTTP |
| Request Headers | @Header, @HeaderMap, @Headers |
| Query Parameters | @Query, @QueryMap, @QueryName |
| Path Parameters | @Path |
| Form-Encoded Params | @Field, @FieldMap, @FormUrlEncoded |
| Request Body | @Body |
| File Upload | @Multipart, @Part, @PartMap |
| URL Parameters | @Url |
For details, refer to the official documentation: Retrofit Official Documentation
This component automatically adapts HTTP responses to the return types defined in Java interfaces. The following return types are supported:
Call<T>: Returns the Call<T> object directly without adaptation.String: Adapts the Response Body to a String.Long/Integer/Boolean/Float/Double): Adapts the Response Body to the specified primitive type.CompletableFuture<T>: Adapts the Response Body to a CompletableFuture<T>.Void: Use for requests where the return type is irrelevant.Response<T>: Adapts the response to a Response<T> object.Mono<T>: Reactive return type for Project Reactor.Single<T>: Reactive return type for RxJava (supports RxJava2/RxJava3).Completable: RxJava reactive return type for HTTP requests with no response body (supports RxJava2/RxJava3).Response Body to the specified POJO.Retrofit uses CallAdapterFactory to adapt Call<T> objects to method return types. This component extends CallAdapterFactory with the following implementations:
BodyCallAdapterFactory:
ResponseCallAdapterFactory:
Retrofit.Response<T>.Retrofit.Response<T>.Reactive Programming CallAdapterFactory:
Mono<T>, Single<T>, and Completable.Custom adaptations can be implemented by extending CallAdapter.Factory. Configure global call adapter factories via retrofit.global-call-adapter-factories:
retrofit:
# Global adapter factories (component-extended CallAdapterFactories are pre-included; do not reconfigure here)
global-call-adapter-factories:
# ...
For individual interfaces, specify CallAdapter.Factory using @RetrofitClient.callAdapterFactories.
Retrofit uses Converter to convert @Body-annotated objects to HTTP request bodies and response bodies to Java objects. Supported converters include:
com.squareup.Retrofit:converter-gsoncom.squareup.Retrofit:converter-jacksoncom.squareup.Retrofit:converter-moshicom.squareup.Retrofit:converter-protobufcom.squareup.Retrofit:converter-wirecom.squareup.Retrofit:converter-simplexmlcom.squareup.retrofit2:converter-jaxbcom.alibaba.fastjson.support.retrofit.Retrofit2ConverterFactoryConfigure global Converter.Factory via retrofit.global-converter-factories (default: retrofit2.converter.jackson.JacksonConverterFactory).
To customize Jackson configuration, override the JacksonConverterFactory bean:
retrofit:
# Global converter factories
global-converter-factories:
- retrofit2.converter.jackson.JacksonConverterFactory
For individual interfaces, specify Converter.Factory using @RetrofitClient.converterFactories.
Note: If the API returns a raw String text that cannot be converted using a JSON converter, you can use StringConverterFactory, which will directly convert the result to a String and return it.
Timeout configurations for OkHttpClient can be set via the @Timeout annotation or global configuration retrofit.global-timeout. For advanced configurations, customize OkHttpClient as follows:
SourceOkHttpClientRegistrar@Component
public class CustomOkHttpClientRegistrar implements SourceOkHttpClientRegistrar {
@Override
public void register(SourceOkHttpClientRegistry registry) {
// Register customOkHttpClient with 1-second timeouts
registry.register("customOkHttpClient", new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(1))
.writeTimeout(Duration.ofSeconds(1))
.readTimeout(Duration.ofSeconds(1))
.addInterceptor(chain -> chain.proceed(chain.request()))
.build());
}
}
OkHttpClient in @RetrofitClient@RetrofitClient(baseUrl = "${test.baseUrl}", sourceOkHttpClient = "customOkHttpClient")
public interface CustomOkHttpUserService {
/**
* Query user info by ID
*/
@GET("getUser")
User getUser(@Query("id") Long id);
}
The component supports configuring timeouts via the @Timeout annotation at both the interface (class-level) and method (method-level) levels, with higher priority than global timeout properties.
Priority chain: method @Timeout → class @Timeout → global GlobalTimeoutProperty
@Timeout(readTimeoutMs = 1000, writeTimeoutMs = 1000)
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface UserService {
@GET("getUser")
User getUser(@Query("id") Long id);
@Timeout(readTimeoutMs = 5000)
@GET("getUserSlow")
User getUserSlow(@Query("id") Long id);
}
Annotation attribute default value -1 (Constants.INVALID_VALUE) means "not configured, inherit from upper level"; 0 means "no timeout"; positive value means timeout in milliseconds.
@Timeout: processed at OkHttpClient creation time, zero runtime overhead@Timeout: TimeoutCallFactory pre-creates per-method OkHttpClient clones, looked up via Invocation tag at runtime; interfaces without method-level @Timeout have zero extra overheadAllows users to register a Spring Bean to customize the Call.Factory used by each @RetrofitClient interface. The framework passes the fully-configured OkHttpClient (with all interceptors, timeouts, connection pool, etc.) as a parameter. When no Bean is registered, the component behavior remains unchanged.
@Component
public class MyCallFactoryConfigurer implements CallFactoryConfigurer {
@Override
public Call.Factory configure(Class<?> retrofitInterface, OkHttpClient baseClient) {
// Derive from baseClient via newBuilder (e.g., dynamic callTimeout)
if (retrofitInterface == UserService.class) {
return baseClient.newBuilder()
.callTimeout(5, TimeUnit.SECONDS)
.build();
}
// Return baseClient directly (equivalent to default behavior)
return baseClient;
}
}
When
CallFactoryConfigurerreturns a non-OkHttpClientinstance, method-level@Timeoutwill not take effect — users should handle timeouts in their custom implementation.
The component supports global and declarative logging.
Global logging is disabled by default (enable=false) and must be turned on explicitly. Once enabled, the default BASIC strategy logs only request/response lines (status code and elapsed time), with negligible overhead. Default configu
$ claude mcp add retrofit-spring-boot-starter \
-- python -m otcore.mcp_server <graph>