【发布时间】:2017-06-10 14:37:47
【问题描述】:
假设有以下 Spring 配置,其中 genericDirectory 占位符在编译时是未知的:
@Configuration
@PropertySource("${genericDirectory}/additional.properties")
public class SomeConfiguration{
//...
}
我尝试在刷新上下文之前添加属性,但仍然出现异常
public static BeanFactory createContext(String genericDirectoryName) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("genericDirectory", genericDirectoryName);
configurer.setProperties(props);
applicationContext.addBeanFactoryPostProcessor(configurer);
applicationContext.register(SomeConfiguration.class);
applicationContext.refresh(); // throws IllegalArgumentException: Could not resolve placeholder 'genericDirectory'
return applicationContext;
}
我还尝试在父上下文中设置属性并通过setParent 方法将其传递给子级,但没有成功(遇到相同的异常)。
请展示如何在运行时向 ApplicationContext 添加属性。
PS。在这种情况下没有隐藏配置 - 上下文是按原样手动创建的。
【问题讨论】:
-
那永远行不通。
@PropertySource注释中的占位符仅针对环境变量和系统变量解析,而不针对其他属性。所以你需要用System.setProperty设置它来解决它。或者不是使用@PropertySource,而是根据传入的属性手动添加ResourcePropertySource。 -
@M.Denium,非常感谢!
System.setProperty也是一种可接受的方式。如果您希望评论可以成为答案。
标签: java spring properties configuration applicationcontext