Add rest-client-test module: @RestClientTest on Boot 4.1, Jackson 3 by default, and the RestClient-vs-RestTemplate root-URI matching trap (post #49)
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
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.
|
||||
*
|
||||
* <p>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).</p>
|
||||
*/
|
||||
@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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user