繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM