2015-01-20 72 views
0

我希望在通過XML配置刷新上下文之前將PropertySource添加到Spring Environment在上下文刷新之前手動添加@PropertySource:配置環境

Java的配置方式做到這一點是:

@Configuration 
@PropertySource("classpath:....") 
public ConfigStuff { 
    // config 
} 

和猜測神奇地@PropertySource將上下文刷新/初始化之前進行處理。

但是我想做一些更加動態的東西,而不僅僅是從classpath加載。

我知道如何配置Environment前上下文刷新的唯一途徑是實現ApplicationContextInitializer<ConfigurableApplicationContext>寄存器它。

我強調寄存器部分,因爲這需要通過servlet上下文告訴您的環境關於上下文初始值設定項和/或在單元測試的情況下爲每個單元測試添加@ContextConfiguration(value="this I don't mind", initializers="this I don't want to specify")

我寧願我的自定義初始化程序或真正在我的情況下自定義PropertySource通過應用程序上下文xml文件在正確的時間加載,就像@PropertySource似乎工作。

+0

此屬性來源是否與佔位符配置器一起使用?你可以用這個bean指定它嗎? – 2015-01-20 23:27:09

+0

不可以,因爲PropertyPlaceholder(包括舊的和新的)不會實際更改'Environment'。我希望在佔位符之前將屬性添加到環境中。 – 2015-01-20 23:32:11

+0

看到這個:http://stackoverflow.com/questions/14416005/spring-environment-property-source-configuration – 2015-01-20 23:34:05

回答

0

看完@PropertySource的加載後,我想出了我需要實現的接口,以便在其他beanPostProcessors運行之前配置環境。訣竅是實施BeanDefinitionRegistryPostProcessor

public class ConfigResourcesEnvironment extends AbstractConfigResourcesFactoryBean implements ServletContextAware, 
    ResourceLoaderAware, EnvironmentAware, BeanDefinitionRegistryPostProcessor { 

    private Environment environment; 

    @Override 
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { 
     if (environment instanceof ConfigurableEnvironment) { 
      ConfigurableEnvironment env = ((ConfigurableEnvironment) this.environment); 
      List<ResourcePropertySource> propertyFiles; 
      try { 
       propertyFiles = getResourcePropertySources(); 
      } catch (IOException e) { 
       throw new RuntimeException(e); 
      } 
      //Spring prefers primacy ordering so we reverse the order of the files. 
      reverse(propertyFiles); 
      for (ResourcePropertySource rp : propertyFiles) { 
       env.getPropertySources().addLast(rp); 
      } 
     } 
    } 

    @Override 
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { 
     //NOOP 
    } 

    @Override 
    public void setEnvironment(Environment environment) { 
     this.environment = environment; 
    } 


} 

我的getResourcePropertySources()是自定義的,所以我沒有打擾顯示它。請注意,這種方法可能無法用於調整環境配置文件。爲此你仍然需要使用初始化器。