如何在使用spring-cloud-config-client时配置自定义RestTemplate?

时间:2015-05-14 13:52:10

标签: java spring spring-cloud spring-cloud-config

我正在尝试使用spring-cloud-config-client在启动时从spring-cloud-config-server应用程序中读取我的配置属性。 我的应用程序是一个Spring-Boot应用程序,我需要做的是在请求发送到配置服务器之前为请求添加一个特定的标头。

我已阅读文档(http://cloud.spring.io/spring-cloud-config/spring-cloud-config.html),但我找不到使用提供的RestTemplate自定义ConfigServicePropertySourceLocator的方法。

最好的方法是什么?

非常感谢

2 个答案:

答案 0 :(得分:2)

扩展@spencergibb答案。

  • 创建配置类。

    @Configuration
    @ConditionalOnClass({ConfigServicePropertySourceLocator.class, RestTemplate.class})
    public class ConfigClientBootstrapConfiguration {
    
        private final ConfigServicePropertySourceLocator locator;
    
        @Autowired
        public ConfigClientBootstrapConfiguration(ConfigServicePropertySourceLocator locator) {
            this.locator = locator;
        }
    
        @PostConstruct
        public void init() {
            RestTemplate restTemplate = new RestTemplate();
            locator.setRestTemplate(restTemplate);
        }
    
    }
    
  • 在子目录bootstrap.factories

    中创建resources/META-INF
    # Bootstrap components
    org.springframework.cloud.bootstrap.BootstrapConfiguration=\
    path.to.config.ConfigClientBootstrapConfiguration
    

答案 1 :(得分:1)

有一个ConfigServicePropertySourceLocator.setRestTemplate()。在您的配置类中添加@PostConstruct方法,您可以在其中设置RestTemplate