I wrote a ClientHttpRequestInterceptor implementation to automatically insert some HttpHeaders into any outgoing request from my Spring Boot service.
One of the headers that I was to support is to indicate the source application that is sending this request. For this, I injected the "spring.application.name" application property into a private variable and used that private variable to set the HttpHeader.
public class ClientHeaderPropagationInterceptor implements ClientHttpRequestInterceptor {
@Value("${spring.application.name}")
private String appName;
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
log.debug("ClientHeaderPropagationInterceptor in action");
// Set source header for traceability between microservices
log.debug("Setting request source to {}", appName);
requestHeaders.set("source", appName);
return execution.execute(request, body);
}
}
But I'm getting a "null" value in the appName variable above. Is this because the Interceptor is initialized before any properties can be injected? Any advice would be much appreciated.
The Interceptor class is inserted into the RestTemplate lifecycle from the @Bean where the RestTemplate is injected:
@Configuration
public class ApplicationConfig {
...
@LoadBalanced
@Bean(name = "loadBalancedRestTemplate")
public RestTemplate getLoadBalancedRestTemplate(){
RestTemplate restTemplate = new RestTemplate(customHttpRequestFactory());
restTemplate.setErrorHandler(new CustomResponseHandler());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
restTemplate.setInterceptors(Collections.singletonList(new ClientHeaderPropagationInterceptor()));
return restTemplate;
}
...
}
I can confirm that the interceptor does get run as I can see the log.debug message but the appName variable is still null.
@Value
will not work for non managed spring beans. First you need to make it spring managed. Try following:
@Bean
public ClientHeaderPropagationInterceptor clientHeaderPropagationInterceptor() {
return new ClientHeaderPropagationInterceptor();
}
@LoadBalanced
@Bean(name = "loadBalancedRestTemplate")
public RestTemplate getLoadBalancedRestTemplate(){
RestTemplate restTemplate = new RestTemplate(customHttpRequestFactory());
restTemplate.setErrorHandler(new CustomResponseHandler());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
restTemplate.setInterceptors(Collections.singletonList(clientHeaderPropagationInterceptor()));
return restTemplate;
}