2015-07-21 55 views
2

有沒有辦法覆蓋通過Spring Cloud Config Server與其他屬性源(特別是系統環境)設置的屬性?我知道我可以通過循環訪問Environment對象的PropertySource來手動執行此操作,但是如果我可以將其設置爲bootstrapConfig來源爲最低優先級,那將是理想的。覆蓋Spring Cloud配置值與環境

+0

你有沒有找到一個方法來做到這一點,而無需編寫自己的應用程序監聽器? –

+0

不,沒有其他辦法可以做到這一點,至少在Spring Boot 1.2.x中不這樣做。我沒有檢查過1.3.x(Spring Cloud Brixton)。 –

回答

1

FWIW,我通過編寫一個自定義的ApplicationListener來完成這個任務,這個自定義的事件在週期早期被觸發,但是在配置服務的PropertySource被加載後。我附上了代碼,以防萬一有興趣。如果有一個「官方」春辦法做到這一點,我仍然有興趣,但這個工程:

package com.example; 

import org.springframework.boot.context.event.ApplicationPreparedEvent; 
import org.springframework.context.ApplicationListener; 
import org.springframework.core.Ordered; 
import org.springframework.core.annotation.Order; 
import org.springframework.core.env.CompositePropertySource; 
import org.springframework.core.env.ConfigurableEnvironment; 
import org.springframework.core.env.MutablePropertySources; 
import org.springframework.core.env.PropertySource; 

@Order(Ordered.HIGHEST_PRECEDENCE) 
public class ConfigServicePropertyDeprioritizer 
     implements ApplicationListener<ApplicationPreparedEvent> 
{ 
    private static final String CONFIG_SOURCE = "bootstrap"; 

    private static final String PRIORITY_SOURCE = "systemEnvironment"; 

    @Override 
    public void onApplicationEvent(ApplicationPreparedEvent event) 
    { 
     ConfigurableEnvironment environment = event.getApplicationContext() 
       .getEnvironment(); 
     MutablePropertySources sources = environment.getPropertySources(); 
     PropertySource<?> bootstrap = findSourceToMove(sources); 

     if (bootstrap != null) 
     { 
      sources.addAfter(PRIORITY_SOURCE, bootstrap); 
     } 
    } 

    private PropertySource<?> findSourceToMove(MutablePropertySources sources) 
    { 
     boolean foundPrioritySource = false; 

     for (PropertySource<?> source : sources) 
     { 
      if (PRIORITY_SOURCE.equals(source.getName())) 
      { 
       foundPrioritySource = true; 
       continue; 
      } 

      if (CONFIG_SOURCE.equals(source.getName())) 
      { 
       // during bootstrapping, the "bootstrap" PropertySource 
       // is a simple MapPropertySource, which we don't want to 
       // use, as it's eventually removed. The real values will 
       // be in a CompositePropertySource 
       if (source instanceof CompositePropertySource) 
       { 
        return foundPrioritySource ? null : source; 
       } 
      } 
     } 

     return null; 
    } 
} 
+0

這是在配置客戶端還是配置服務器中完成的? –

+0

它在客戶端完成。 –