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 
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.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.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 org.springframework.beans.factory.annotation.Value; 
import org.springframework.stereotype.Component; 

public class EmulatorConfig { 
  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); ....
Tags:  Java  Spring 
Last blog articles:
Ubuntu: Login loop
Leaving LinkedIn
LinkedIn: Odcházení
git gui: Add pull and stash commands
Bosch Silence Plus + code E24

Java Ubuntu Gradle česky personal Software-architecture DIY children React Eclipse DisplayLink AI Spring JavaScript AspectJ neuron SSH LXC JavaFX Immutables Gnome3 GIT FatJar Edison technologies science procrastination pokusy linux lambda kvas ellipsis destilace chemie alkohol VisualVM Upstart Tomcat Selenium REST PrimeFaces Log4j Jooq Jackson JSF Debug DI CSS

Last tweets: