Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I default a system property for a constructor-arg in a spring config file?

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>
like image 248
TERACytE Avatar asked Feb 24 '12 18:02

TERACytE


4 Answers

Spring 3.0.x supports a syntax like this:

value="${varName:defaultValue}"

References:

  • SPR-4785
  • Changes in version 3.0.0.RC1 (2009-09-25) (PropertyPlaceholderConfigurer supports "${myKey:myDefaultValue}" defaulting syntax)
like image 55
FrVaBe Avatar answered Nov 19 '22 11:11

FrVaBe


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.

like image 37
TERACytE Avatar answered Nov 19 '22 09:11

TERACytE


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);
}
like image 41
Sebastien Avatar answered Nov 19 '22 09:11

Sebastien


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.

like image 44
jddsantaella Avatar answered Nov 19 '22 09:11

jddsantaella