2015-07-21 57 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

它在客户端完成。 –