MCPcopy Index your code
hub / github.com/LianjiaTech/retrofit-spring-boot-starter

github.com/LianjiaTech/retrofit-spring-boot-starter @4.2.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release 4.2.0 ↗ · + Follow
957 symbols 2,889 edges 184 files 274 documented · 29%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

retrofit-spring-boot-starter

License Maven Central License License Ask DeepWiki

中文文档

retrofit enables the conversion of HTTP APIs into Java interfaces. This component deeply integrates Retrofit with Spring Boot and supports various practical feature enhancements.

  • For Spring Boot 3.x/4.x projects, use retrofit-spring-boot-starter 4.x
  • Since Spring Boot 4.x uses Jackson3 by default, and this component also uses Jackson2 as its default converter, it is recommended to set the global converter to Jackson3 for Spring Boot 4.x projects.
  • Configuration method: retrofit.global-converter-factories=com.github.lianjiatech.retrofit.spring.boot.core.jackson3.Jackson3ConverterFactory
  • For Spring Boot 1.x/2.x projects, use retrofit-spring-boot-starter 2.x, which supports Spring Boot 1.4.2 and above.

🚀 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

Quick Start

Add Dependency

<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:

Manual Auto-configuration Import

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"/>

Define HTTP Java Interface

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, if baseUrl = http://localhost:8080/api/test/: - A method path person results in the full URL: http://localhost:8080/api/test/person. - A method path /person results in the full URL: http://localhost:8080/person.

Injection and Usage

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 Annotations

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

Feature Highlights

Automatic Adaptation of HTTP Responses to Java Return Types

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.
  • By default, JSON Converter is used to convert the bytes of 'Response Body' to String, if you want to directly get the String converted by 'Response Body', you can specify 'Converter.Factory' as ' com.github.lianjiatech.retrofit.spring.boot.core.StringConverterFactory`
  • Primitive Types (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).
  • Custom POJOs: Adapts the Response Body to the specified POJO.

Adaptation Implementation

Retrofit uses CallAdapterFactory to adapt Call<T> objects to method return types. This component extends CallAdapterFactory with the following implementations:

  • BodyCallAdapterFactory:

    • Executes HTTP requests synchronously and adapts the response body to the method's return type.
    • Supports all return types with the lowest priority.
  • ResponseCallAdapterFactory:

    • Executes HTTP requests synchronously and adapts the response to Retrofit.Response<T>.
    • Only applicable when the return type is Retrofit.Response<T>.
  • Reactive Programming CallAdapterFactory:

    • Supports reactive types like 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.

Custom Data Converters

Retrofit uses Converter to convert @Body-annotated objects to HTTP request bodies and response bodies to Java objects. Supported converters include:

  • Gson: com.squareup.Retrofit:converter-gson
  • Jackson: com.squareup.Retrofit:converter-jackson
  • jackson3: com.github.lianjiatech.retrofit.spring.boot.core.jackson3.Jackson3ConverterFactory
  • Moshi: com.squareup.Retrofit:converter-moshi
  • Protobuf: com.squareup.Retrofit:converter-protobuf
  • Wire: com.squareup.Retrofit:converter-wire
  • Simple XML: com.squareup.Retrofit:converter-simplexml
  • JAXB: com.squareup.retrofit2:converter-jaxb
  • FastJson: com.alibaba.fastjson.support.retrofit.Retrofit2ConverterFactory

Configure 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.

Custom OkHttpClient

Timeout configurations for OkHttpClient can be set via the @Timeout annotation or global configuration retrofit.global-timeout. For advanced configurations, customize OkHttpClient as follows:

Implement 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());  
    }  
}  

Specify 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);  
}  

@Timeout Configuration

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.

  • Class-level @Timeout: processed at OkHttpClient creation time, zero runtime overhead
  • Method-level @Timeout: TimeoutCallFactory pre-creates per-method OkHttpClient clones, looked up via Invocation tag at runtime; interfaces without method-level @Timeout have zero extra overhead

CallFactoryConfigurer SPI

Allows 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 CallFactoryConfigurer returns a non-OkHttpClient instance, method-level @Timeout will not take effect — users should handle timeouts in their custom implementation.

Logging

The component supports global and declarative logging.

Global 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

Extension points exported contracts — how you extend this code

CustomErrorDecoderUserService (Interface)
使用自定义 ErrorDecoder 的 service。 @author 陈添明 [13 implementers]
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/errordecoder/CustomErrorDecoderUserService.java
InternalCallAdapterFactory (Interface)
组件内置CallAdapterFactory,标记接口。 @author 陈添明 @since 2022/9/12 8:08 下午 [7 implementers]
src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/InternalCallAdapterFactory.java
PathMatchPrecedenceUserService (Interface)
验证 path-match 拦截器的 include/exclude 优先级:当同一路径同时命中 include 与 exclude, exclude 应优先 — 不执行 doIntercept,没有 path.match 头。 @aut [9 …
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/interceptor/PathMatchPrecedenceUserService.java
SourceOkHttpClientRegistrar (Interface)
SourceOkHttpClientRegistry注册器 @author 陈添明 @since 2022/5/24 8:13 下午 [5 implementers]
src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/SourceOkHttpClientRegistrar.java
AnnotatedActuateService (Interface)
带接口级 @Logging/@Retry 注解、并显式覆盖超时的 client,用于验证 Actuator Endpoint 对 source="interface" 与超时覆盖/继承的解析。 [13 implementers]
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/actuate/AnnotatedActuateService.java
FallbackFactory (Interface)
@author 陈添明 @param the retrofit interface type [5 implementers]
src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/FallbackFactory.java
PlainActuateService (Interface)
不带任何横切注解、且不覆盖超时/连接池的 client,用于验证 Actuator Endpoint 对 source="global" 与超时/连接池完全继承全局的解析。 @author 陈添明 [13 implementers]
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/actuate/PlainActuateService.java
CircuitBreakerConfigRegistrar (Interface)
@author 陈添明 @since 2022/5/24 9:37 下午 [5 implementers]
src/main/java/com/github/lianjiatech/retrofit/spring/boot/degrade/resilience4j/CircuitBreakerConfigRegistrar.java

Core symbols most depended-on inside this repo

Shape

Method 719
Class 171
Interface 63
Enum 4

Languages

Java100%

Modules by API surface

src/main/java/com/github/lianjiatech/retrofit/spring/boot/actuate/RetrofitGlobalInfo.java95 symbols
src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitClientResolution.java88 symbols
src/main/java/com/github/lianjiatech/retrofit/spring/boot/config/RetrofitAutoConfiguration.java37 symbols
src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/RetrofitFactoryBean.java25 symbols
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/metrics/DefaultRetrofitTagsProviderTest.java22 symbols
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/aot/RetrofitAotProcessorTest.java20 symbols
src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/reactive/Rxjava3SingleCallAdapterFactory.java18 symbols
src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/reactive/Rxjava2SingleCallAdapterFactory.java18 symbols
src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/reactive/MonoCallAdapterFactory.java18 symbols
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/log/LogStrategyTest.java16 symbols
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/actuate/RetrofitEndpointTest.java13 symbols
src/test/java/com/github/lianjiatech/retrofit/spring/boot/test/integration/timeout/MethodTimeoutServices.java12 symbols

For agents

$ claude mcp add retrofit-spring-boot-starter \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page