Add dynamic properties into Spring using annotations

I am working on command line application and I wanted to pass parameters from command line (read using Commons CLI) to member variables using annotation @Value.

  1. Put your properties into standard Java Properties
  2. Do not pass parameter to AnnotationConfigApplicationContext constructor, but register your configuration manually
  3. Add your properties wrapped by PropertiesPropertySource into ConfigurableEnvironment
  4. Create bean of class PropertySourcesPlaceholderConfigurer (This is crucial!!!). Without this step it was possible to lookup my properties using env.resolvePlaceholder(…) but not using annotation @Value.
package my.test; import 
java.util.Properties; 
import org.springframework.context.annotation.AnnotationConfigApplicationContext; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 
import org.springframework.core.env.PropertiesPropertySource;

@Configuration @ComponentScan(value = { "my.test.components" }) 
public class DIConfiguration { 
  public static AnnotationConfigApplicationContext createContext(Properties properties) {
    PropertiesPropertySource propertiesSource = new PropertiesPropertySource("test", properties);

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.getEnvironment().getPropertySources().addLast(propertiesSource); 
    context.register(DIConfiguration.class); context.refresh(); 

    return context; 
  } 
  
  public DIConfiguration() {
  } 
  
  @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer(); 
  }
}

Then simply annotate your fields:

package my.test.components; 
import java.io.File; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.stereotype.Component; 

@Component 
public class EmulatorConfig { 
  @Value("${test.testFile}") 
  private File testFile; 
}

And use it:

Properties properties = new Properties(); //in real case fill properties by command line parameters 

properties.put("test.testFile", new File("test.txt")); 
properties.put("test.testInt", 15); 
properties.put("test.testBool", true);

AnnotationConfigApplicationContext context = DIConfiguration.createContext(properties); ....
Last blog articles:
Hello Ruby: Dobrodružné programování
Edison EdBlocks: Using remote control
Edison 2.0 received!
JS debug: visually compare two objects or JSONs in browser
4 tips to return multiple values

Last tweets: