Spring 在运行时添加占位符值

Spring add placeholder value at runtime

假设有以下 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 中使用占位符时,这些占位符仅针对环境变量或系统变量(通过 -D 传递给您的程序的变量)进行解析。

所以不要做你现在做的事情,而只是简单地调用 System.setProperty

public static BeanFactory createContext(String genericDirectoryName) {
    System.setProperty("genericDirectory", genericDirectoryName);

   AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
   applicationContext.refresh(); 
   return applicationContext;
}

这应该让正在解析的属性。

要使 @PropertySource 正常工作,您还需要在配置中注册 PropertySourcesPlaceHolderConfigurer