Reputation: 15274
I've been assuming stuff and seeing that now it's not correct. I have the following configuration properties declaration in my spring context :
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="locations">
<list>
<value>classpath:/app.properties</value>
</list>
</property>
</bean>
I thought values from app.properties
would override my system properties so I would be able to acess them directly in my Java classes like this :
String someThingFromPropertyFile = System.getProperty("nameFromPropertyFile");
And of course I get null pointer exceptions all over the place. Now I'm here to ask how to access your application properties from you application (Java classes part of your application).
Is there a better way than this below (I'm not saying it's bad).
Access properties file programmatically with Spring?
Upvotes: 1
Views: 4778
Reputation: 3373
Spring
properties do not override System
properties. It works the other way. You should be getting all your properties from Spring
and not from System.getProperties()
. System
properties will override Spring
properties with the same name. The SYSTEM_PROPERTIES_MODE_OVERRIDE
you are setting says that when you get a property value from Spring
the System
property will win.
You want to set the value to be SYSTEM_PROPERTIES_MODE_FALLBACK
. This is the default so you don't actually need to set it.
If you have this in mind, @NimChimpsky has it the correct method for accessing property values:
@Value("${nameFromPropertyFileOrSystemProperty}")
private String someThingFromProperty;
Upvotes: 0
Reputation: 47290
In app context :
<context:property-placeholder location="classpath:your.properties" ignore-unresolvable="true"/>
then in java you can do this :
@Value("${cities}")
private String cities;
where the your.properties contains this :
cities = my test string
Upvotes: 6