首页 > 解决方案 > 覆盖应用于 RestTemplate 的 RestTemplateCustomizer

问题描述

我正在为我的一个应用程序RestTemplateCustomizer配置通用配置RestTemplate。但是现在在我的一个客户端类中,我需要用另一个自定义拦截器覆盖我拥有的一个自定义拦截器。

我可以在RestTemplate不使用的情况下获得实例,RestTemplateBuilder并在此处添加我的所有配置,这应该可以工作,但我真的不想要这种方法。

我想解决这个问题的方法是将所有拦截器附加到RestTemplate,找到我的自定义拦截器 1,将其删除并添加新的自定义拦截器 2。

 public MyRestClient( RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
        for(int i=0 ;i<this.restTemplate.getInterceptors().size();i++) {    
            if(this.restTemplate.getInterceptors().get(i).getClass().getSimpleName().equalsIgnoreCase("MyCustomInterceptor1")){
                this.restTemplate.getInterceptors().remove(i);
            }

        }

        this.restTemplate.getInterceptors().add(new MyCustomInterceptor2());
    }

它似乎工作正常,但有没有更好的方法来做到这一点?

标签: javaspring-bootresttemplateapache-httpclient-4.x

解决方案


推荐阅读