1

I'm using Spring 4.1.6. I have something like the following:

foo.properties:

valueX=a
valueY=b

Spring bean:

<context:property-placeholder location="classpath:foo.properties" ignore-unresolvable="false" ignore-resource-not-found="false" />

    <bean id="foo" class="com.foo.bar.MyClass" >
        <property name="someValue" value="${valueX}" />
    </bean>

I have a non-Spring class which also needs to use a value from foo.properties.

Non Spring Class:

public void doSomething() {
  String valueY = System.getProperty("valueY");
}

When Spring loads foo.properties, is there a way to populate all the properties into System properties so that I can get "valueY" using System.getProperty("valueY").

I don't want to load foo.properties again in my non-Spring class.

serverfaces
  • 1,155
  • 4
  • 22
  • 49
  • How about this ? http://stackoverflow.com/questions/3339736/set-system-property-with-spring-configuration-file – ArunM Jul 05 '15 at 05:48

1 Answers1

0

The context:property-placeholder will create a PropertySourcesPlaceholderConfigurer config bean for you. You cannot access the properties from this bean programatically as stated here.

What you can do is to load the properties into a separate spring bean as given below.

@Bean(name = "mapper")
public PropertiesFactoryBean mapper() {
  PropertiesFactoryBean bean = new PropertiesFactoryBean();
  bean.setLocation(new ClassPathResource("application.properties"));
  return bean;
}

and then set the system property when the context load is finished using a listener as given below. Got the code from this answer

@Component
public class YourJobClass implements ApplicationListener<ContextRefreshedEvent> {

    @Resource(name = "mapper")
    private Properties myTranslator;

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.setProperties(myTranslator);
    }
}
Community
  • 1
  • 1
ArunM
  • 2,274
  • 3
  • 25
  • 47