微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以定义自定义休息模板?

如何解决是否可以定义自定义休息模板?

我正在尝试定义一个用于我所有应用程序的通用 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?