【问题标题】:Is it possible to define a custom rest template?是否可以定义自定义休息模板?
【发布时间】:2021-03-31 12:37:54
【问题描述】:

我正在尝试定义一个用于我所有应用程序的通用 bean,以便在记录器和其他逻辑中添加。我的想法是:

public class MyRestTemplate extends RestTemplate{

然后:

@Configuration
public class RestTemplateConfig {

   @Bean
   public MyRestTemplate myRestTemplate(RestTemplateBuilder builder){ 
       return (MyRestTemplate) builder.build(); //throws classcast exception!
   }
}

我做错了什么?还有其他方法吗?我想确保人们必须使用我的自定义类。

【问题讨论】:

标签: spring-boot spring-mvc resttemplate


【解决方案1】:

如果您想在 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();
}

【讨论】:

  • 但是这样我只会自定义一个自定义器,开发者必须使用这个自定义创建一个rest模板
【解决方案2】:

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

【讨论】:

  • 这个答案与问题无关。 @Phate 希望有一个 RestTemplate 的自定义实例,而不是默认实例。
猜你喜欢
  • 2021-09-14
  • 1970-01-01
  • 2015-09-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
相关资源
最近更新 更多