Настройте RestTemplate с RestTemplateBuilder
1. Вступление
В этом кратком руководстве мы рассмотримhow to configure a Spring RestTemplate bean.
Начнем с обсуждения трех основных типов конфигурации:
-
используя значение по умолчаниюRestTemplateBuilder
-
используяRestTemplateCustomizer
-
создание нашего собственногоRestTemplateBuilder
Чтобы легко это проверить, следуйте инструкциям поhow to set up a simple Spring Boot application.
2. Конфигурация с использованием значения по умолчаниюRestTemplateBuilder
Чтобы настроитьRestTemplate таким образом, нам нужно добавитьinject the default RestTemplateBuilder bean provided by Spring Boot в наши классы:
private RestTemplate restTemplate;
@Autowired
public HelloController(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
RestTemplate bean, созданный с помощью этого метода, имеет свойscope limited to the class in which we build it.
3. Конфигурация с использованиемRestTemplateCustomizer
При таком подходе мы можемcreate an application-wide, additive customization.
Это немного более сложный подход. Для этого нам нужноcreate a class that implements RestTemplateCustomizer, and определить его как bean-компонент:
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor());
}
}
СинтерцепторCustomClientHttpRequestInterceptor выполняет базовую запись запроса:
public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private static Logger LOGGER = LoggerFactory
.getLogger(CustomClientHttpRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(
HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
logRequestDetails(request);
return execution.execute(request, body);
}
private void logRequestDetails(HttpRequest request) {
LOGGER.info("Headers: {}", request.getHeaders());
LOGGER.info("Request Method: {}", request.getMethod());
LOGGER.info("Request URI: {}", request.getURI());
}
}
Теперь мы определяемCustomRestTemplateCustomizer как bean-компонент в классе конфигурации или в нашем классе приложения Spring Boot:
@Bean
public CustomRestTemplateCustomizer customRestTemplateCustomizer() {
return new CustomRestTemplateCustomizer();
}
В этой конфигурацииevery RestTemplate that we’ll use in our application will have the custom interceptor set on it.
4. Конфигурация путем создания собственныхRestTemplateBuilder
Это наиболее экстремальный подход к настройкеRestTemplate. Itdisables the default auto-configuration of RestTemplateBuilder, so we need to define it ourselves:
@Bean
@DependsOn(value = {"customRestTemplateCustomizer"})
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder(customRestTemplateCustomizer());
}
После этого мы можем использоватьinject the custom builder в наших классах, как мы сделали бы сRestTemplateBuilder по умолчанию, и создатьRestTemplate как обычно:
private RestTemplate restTemplate;
@Autowired
public HelloController(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
5. Заключение
Мы видели, как настроитьRestTemplate со значением по умолчаниюRestTemplateBuilder, создав наш собственныйRestTemplateBuilder, или используя компонентRestTemplateCustomizer.
Как всегда, полную кодовую базу для этого примера можно найти в нашемGitHub repository.