0

I want to inject property values into the Spring context when it is started. I am trying to do this using the new Environment and PropertySource features of Spring 3.1.

In the class in which loads the Spring context, I define my own PropertySource class as follows:

private static class CustomPropertySource extends PropertySource<String> {
   public CustomPropertySource() {super("custom");}
      @Override
      public String getProperty(String name) {
      if (name.equals("region")) {
         return "LONDON";
      }
      return null;
}

Then, I add this property source to the application context:

ClassPathXmlApplicationContext springIntegrationContext = 
   new ClassPathXmlApplicationContext("classpath:META-INF/spring/ds-spring-intg-context.xml");
context.getEnvironment().getPropertySources().addLast( new CustomPropertySource());
context.refresh();
context.start();

In one of my beans, I try to access the property value:

@Value("${region}")
public void setRegion(String v){
   ...
}

bur recieve the folowing error:

java.lang.IllegalArgumentException: Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'region' in string value [${region}]

Any help is greatly appreciated

incomplete-co.de
  • 2,137
  • 18
  • 23
user1052610
  • 4,440
  • 13
  • 50
  • 101

1 Answers1

1

when you pass an XML file location as a constructor argument to ClassPathXmlApplicationContext(..) it straight away does the context.refresh()/context.start() methods. so by passing in your XML locations, you're essentially doing it all in one pass and the context is already started/loaded by the time you get to call context.getEnvironment().getPropertySources....

try this;

ClassPathXmlApplicationContext springIntegrationContext = 
   new ClassPathXmlApplicationContext();
context.getEnvironment().getPropertySources().addLast( new CustomPropertySource());
context.setLocations("classpath:META-INF/spring/ds-spring-intg-context.xml");
context.refresh();

it will set your sources, then your xml, then start the app context.

incomplete-co.de
  • 2,137
  • 18
  • 23