Skip to content

Instantly share code, notes, and snippets.

@justin-lyon
Last active October 5, 2020 20:09
Show Gist options
  • Save justin-lyon/a255af87ab219e09575d56483827fb3e to your computer and use it in GitHub Desktop.
Save justin-lyon/a255af87ab219e09575d56483827fb3e to your computer and use it in GitHub Desktop.
Access @ConfigurationProperties from a ClientHttpRequestInterceptor implementation?
@Configuration
@ConfigurationProperties(prefix = "myprops")
public class MyConfigProps {
@NotBlank
private String prop1;
// ...get/set
}
@Component
public class MyRestTemplateInterceptor implements ClientHttpRequestInterceptor {
@Autowired
private MyConfigProps myConfigProps; // A @ConfigurationProperties Class
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
System.out.println(myConfigProps); // -> NULL
return execution.execute(request, body);
}
}
@Configuration
public class RestTemplateConfiguration {
@Bean
public RestTemplate restTemplate() {
RestTemplate template = new RestTemplate();
restTemplate.setInterceptors(List.of(new MyRestTemplateInterceptor());
return template;
}
}
@justin-lyon
Copy link
Author

As succinctly as possible, Why is the config null on line 9 in MyRestTemplateInterceptor?

I need to reference my @ConfigurationProperties within the Interceptor implementation, but I don't see how to declare the dependency such that it is automatically injected like other beans.

To rephrase: How to inject a dependency to a resttemplate's interceptor?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment