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.core.env.PropertiesPropertySource;

@ComponentScan(value = {
public class DIConfiguration {

public static AnnotationConfigApplicationContext createContext(Properties properties) {
 PropertiesPropertySource propertiesSource = new PropertiesPropertySource("test", properties);

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

return context;

public DIConfiguration() {

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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s