【问题标题】:Spring add placeholder value at runtimeSpring在运行时添加占位符值
【发布时间】: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


【解决方案1】:

解析属性不是一个多遍过程。在@PropertySource 中使用占位符时,这些仅针对环境变量或系统变量(与-D 一起传递给您的程序的变量)解析。

因此,与其做你现在所做的,不如直接调用System.setProperty

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

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

这应该让属性被解析。

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

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 2020-06-26
    • 2012-07-18
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2012-03-08
    • 2012-09-13
    相关资源
    最近更新 更多