简体   繁体   中英

Spring add placeholder value at runtime

Suppose having the following Spring configuration where genericDirectory placeholder is unknown at compile time:

@Configuration
@PropertySource("${genericDirectory}/additional.properties")
public class SomeConfiguration{
  //...
}

I tried to add a property before refreshing context, but still get exception

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;
}

I also tried to set the property in parent context and pass it to child via setParent method, but didn't succeed (got the same exception).

Please, show how to add a property to ApplicationContext in runtime.

PS. there's no hidden configuration in this case - context is created manually as is.

Resolving properties isn't a multi pass process. When using placeholders in @PropertySource those are only resolved against environment variables or system variables (the ones passed with -D to your program).

So instead of doing what you have now instead just simply call System.setProperty .

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

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

This should let the attribute being resolved.

Also to actually make the @PropertySource work you also need to register a PropertySourcesPlaceHolderConfigurer in your configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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