I have a spring config file which includes the following elements:
<context:property-placeholder location="classpath:default.properties"/>
<bean id="theVar" class="java.lang.String">
<constructor-arg value="${varName}"/>
</bean>
"varName" is now moved from the properties file to a system property. It is being added when I start a Maven build:
mvn clean install -DvarName=data
I want to also run my build without specifying varName:
mvn clean install
Is there some way to default varName in my spring config? Though this does not work, a conceptual example of what I am looking for is:
<bean id="theVar" class="java.lang.String">
<constructor-arg value="${varName}" default="theDefaultValue"/>
</bean>
Spring 3.0.x supports a syntax like this:
value="${varName:defaultValue}"
References:
It turns out that in spring v2.5+, if there is a system property defined, it can be used instead of a property defined in the properties file. You just need to ensure the same name is used and that the 'override' option is enabled.
For example, given:
<!-- my spring config file -->
<context:property-placeholder location="classpath:default.properties" system-properties-mode="OVERRIDE"/>
And:
# default.properties file
theVariable=One
When I execute:
mvn clean install
"One" is picked-up for theVariable. If I execute:
mvn clean install -DtheVariable=Two
"Two" is picked-up instead.
I'm not sure If this will help but if you are annotating classes and want a default value when a system property is not present this is what I currently do:
@Value("#{systemProperties['fee.cc']?:'0.0225'}")
public void setCcFeePercentage(BigDecimal ccFeePercentage) {
this.setCcFeePercentage(ccFeePercentage);
}
It can be done as @sebastien has described but in the configuration file as you want:
<bean id="theVar" class="java.lang.String">
<constructor-arg value="#{systemProperties['varName'] == null ? 'default_value' : systemProperties['varName']}"/>
</bean>
If your varName
variable is not present, default value will be set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With