如何解决是否可以定义自定义休息模板?
我正在尝试定义一个用于我所有应用程序的通用 bean,以便在记录器和其他逻辑中添加。我的想法是:
public class MyRestTemplate extends RestTemplate{
那么:
@Configuration
public class RestTemplateConfig {
@Bean
public MyRestTemplate myRestTemplate(RestTemplateBuilder builder){
return (MyRestTemplate) builder.build(); //throws classcast exception!
}
}
我做错了什么?还有其他方法吗?我想确保人们将不得不使用我定制的课程。
解决方法
builder.build()
返回 RestTemplate
,而不是 MyRestTemplate
。
如果您按如下所示更改代码,您将创建一个名为 myRestTemplate
的 bean。如果您没有在 @Bean
注释中覆盖它,Spring 会使用该方法的名称作为 bean 名称。
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate myRestTemplate(RestTemplateBuilder builder){
return builder.build(); //throws classcast exception!
}
}
另请参阅https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/boot-features-restclient.html
,如果您想在您的 restTemplate 中进行一些自定义,您可以定义一个实现 RestTemplateCustomizer 的类并为其添加自定义拦截器。
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor());
}
}
然后你必须为所有从这个 restTemplate 发出的请求定义自定义拦截器
public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request,byte[] body,ClientHttpRequestExecution execution) throws IOException {
// This is where you can do a lot of thing with this request like logging
return execution.execute(request,body);
}
}
最后,只需为您编写的自定义 restTemplate 定义一个 bean
@Bean
public CustomRestTemplateCustomizer customRestTemplateCustomizer() {
return new CustomRestTemplateCustomizer();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。