Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify a default property value in Spring XML?

We are using a PropertyPlaceholderConfigurer to use java properties in our Spring configuration (details here)

eg:

<foo name="port">   <value>${my.server.port}</value> </foo> 

We would like to add an additional property, but have a distributed system where existing instances could all use a default value. Is there a way to avoid updating all of our properties files, by indicating a default value in the Spring config for when there isn't an overriding property value defined?

like image 636
Rog Avatar asked Mar 25 '10 06:03

Rog


People also ask

How do I set default value in spring?

To set a default value for primitive types such as boolean and int, we use the literal value: @Value("${some. key:true}") private boolean booleanWithDefaultValue; @Value("${some.

What is the use of default value in the properties?

The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created. For example, if you set the DefaultValue property for a text box control to =Now(), the control displays the current date and time.

What is @value annotation in spring?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.


2 Answers

Spring 3 supports ${my.server.port:defaultValue} syntax.

like image 126
lexicore Avatar answered Sep 24 '22 10:09

lexicore


There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:

config.properties:

timeout.default=30 timeout.myBean=60 

context.xml:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">     <property name="location">         <value>config.properties</value>     </property> </bean>  <bean id="myBean" class="Test">     <property name="timeout" value="${timeout.myBean:${timeout.default}}" /> </bean> 

To use the default while still being able to easily override later, do this in config.properties:

timeout.myBean = ${timeout.default} 
like image 41
Michael Böckling Avatar answered Sep 24 '22 10:09

Michael Böckling