2015-01-20 66 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()是自定义的,所以我没有打扰显示它。请注意,这种方法可能无法用于调整环境配置文件。为此你仍然需要使用初始化器。