package com.ankurm.restclienttest; import org.springframework.stereotype.Service; import org.springframework.web.client.RestClient; /** * Fetches employee data from the external HR system using Spring's fluent {@code RestClient} - * the recommended approach for new client code. Every successful fetch is audited through * {@link EmployeeAuditLogger}, a plain collaborator bean unrelated to REST at all. * *
The client builds itself from an injected {@code RestClient.Builder}, the same shape as * {@link EmployeeTemplateClient}'s {@code RestTemplateBuilder} constructor - this is what lets * {@code @RestClientTest} wire a mocked client straight in, with no separate {@code RestClient} * bean required (see {@link EmployeeHttpInterface} for the one case that does need one).
*/ @Service public class EmployeeClient { private final RestClient restClient; private final EmployeeAuditLogger auditLogger; public EmployeeClient(RestClient.Builder restClientBuilder, EmployeeAuditLogger auditLogger) { this.restClient = restClientBuilder.baseUrl("http://hr-api.example.com").build(); this.auditLogger = auditLogger; } public Employee getEmployeeById(Integer id) { Employee employee = restClient.get() .uri("/employees/{id}", id) .retrieve() .body(Employee.class); auditLogger.logFetch(id); return employee; } }