Spring Boot RestClient as a singleton or create new instances per request

Looking through the documentation here, the expected pattern to use for RestClient is to autowire the RestClient.Builder and then build the RestClient in the constructor method of a service. While this works great when using in a regular class, it does not work as well when testing.

According to the documentation here, the @RestClientTest and @AutoConfigureMockRestServiceServer are usable when there is only 1 builder used within your application. As more instances are created and specific customization is needed, it becomes apparent that you will want to have more than one RestClient.Builder for each specific service.

With this, the only way that I can see to configure it is to bind the MockRestServiceServer to each RestClient.Builder making having them as beans seem to be the obvious route. Now you can have some code like the following:

Configuration logic:

@RequiredArgsConstructor
@Configuration
public class RestClientConfiguration {
    private final RestClientBuilderConfigurer restClientBuilderConfigurer;

    @Bean
    RestClient.Builder microservice1RestClientBuilder() {
        return createDefaultRestClientBuilder()
                .baseUrl("https://localhost:8081");
    }

    /**
     * Copied from
     * {@link org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration
     * RestClientAutoConfiguration}
     * 
     * @return
     */
    private RestClient.Builder createDefaultRestClientBuilder() {
        RestClient.Builder builder = RestClient
                .builder()
                .requestFactory(ClientHttpRequestFactories.get(ClientHttpRequestFactorySettings.DEFAULTS));
        return restClientBuilderConfigurer.configure(builder);
    }
}

Controller logic:

@RequiredArgsConstructor
@RestController
public class MainController {
    private final MainService mainService;

    @GetMapping
    public String hello() {
        return mainService.helloService();
    }
}

Service logic:

@Service
public class MainService {
    private final RestClient restClient;
    
    public MainService(RestClient.Builder microservice1RestClientBuilder) {
        super();
        restClient = microservice1RestClientBuilder.build();
    }

    public String helloService() {
        return restClient.get().uri("/").retrieve().body(String.class);
    }
}

Test logic:

@SpringBootTest
@AutoConfigureMockMvc
class MainControllerTest {
    private MockRestServiceServer microservice1Server;

    @Autowired
    private RestClient.Builder microservice1RestClientBuilder;

    @Autowired
    private MockMvc mvc;

    @BeforeEach
    void init() {
        microservice1Server = MockRestServiceServer.bindTo(microservice1RestClientBuilder).build();
    }

    @Test
    void test() throws Exception {
        microservice1Server
                .expect(requestTo("http://localhost:8081/"))
                .andRespond(withSuccess("Hello world", MediaType.TEXT_PLAIN));
        mvc.perform(get("/")).andExpect(status().is2xxSuccessful()).andExpect(content().string("Hello world"));
    }
}

This all seems like it should work, but it does not because the test will not bind before the RestClient is created. To fix this, the service class can be changed to the following and the test will begin to work.

@RequiredArgsConstructor
@Service
public class MainService {
    private final RestClient.Builder microservice1RestClientBuilder;

    public String helloService() {
        return microservice1RestClientBuilder.build().get().uri("/").retrieve().body(String.class);
    }
}

The test case works now however the RestClient is now created per call which feels unnecessary. This makes me believe either I am missing how it is expected to be used or there is a gap somewhere. My hope with this question is to show the optimal way to use RestClient not only for general usage but also for testing purposes.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật