在通过XML刷新上下文之前,我想在SpringEnvironment中添加一个PropertySource。
这样做的Java配置方法是:
@Configuration
@PropertySource("classpath:....")
public ConfigStuff {
// config
}并猜测在上下文刷新/初始化之前,将以某种方式神奇地处理@PropertySource。
然而,我想做一些更动态的事情,而不仅仅是从类路径加载。
在刷新上下文之前,我知道如何配置Environment的唯一方法是实现ApplicationContextInitializer<ConfigurableApplicationContext>和寄存器。
我强调寄存器部分,因为这需要通过servlet上下文和/或在单元测试的情况下通过servlet上下文告诉您的环境上下文初始化器,并为每个单元测试添加@ContextConfiguration(value="this I don't mind", initializers="this I don't want to specify")。
我更希望我的自定义初始化程序,或者在我的情况下,在正确的时间通过应用程序上下文xml文件加载自定义PropertySource,就像@PropertySource的工作方式一样。
发布于 2015-01-21 21:18:10
在查看了@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()是自定义的,所以我不想展示它。请注意,此方法可能不适用于调整环境配置文件。为此,您仍然需要使用初始化器。
https://stackoverflow.com/questions/28057056
复制相似问题