手动添加一个@PropertySource: Configuring Environment before context is refreshed

Manually add a @PropertySource: Configuring Environment before context is refreshed

我想在通过 XML 配置刷新上下文之前将 PropertySource 添加到 Spring Environment

执行此操作的 Java 配置方法是:

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

并且神奇地猜测 @PropertySource 将在上下文 refreshed/initialized.

之前被处理

但是我想做一些比仅仅从类路径加载更动态的东西。

我知道如何在刷新上下文之前配置 Environment 的唯一方法是实现 ApplicationContextInitializer<ConfigurableApplicationContext> 注册 它。

我强调寄存器部分,因为这需要通过 servlet 上下文 and/or 告诉您的环境有关上下文初始值设定项的情况,以防单元测试为每个单元测试添加 @ContextConfiguration(value="this I don't mind", initializers="this I don't want to specify")

我宁愿我的自定义初始化器或在我的情况下,自定义 PropertySource 在正确的时间通过应用程序上下文 xml 文件加载,就像 @PropertySource 看起来如何工作一样。

在查看@PropertySource 的加载方式后,我弄清楚了我需要实现哪个接口,以便我可以在其他 beanPostProcessor 之前配置环境 运行。诀窍是实施 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() 是自定义的,所以我懒得展示它。作为旁注,此方法可能不适用于调整环境配置文件。为此,您仍然需要使用初始化程序。