Using Default Values for Properties in Spring

Defaults for Property Values? I didn’t know that?

I was looking through the Spring Greenhouse application and discovered an existing feature that I was unaware of. We can set a default value when configuring PropertyPlaceholderConfigurer.

1. Set the default value separator in config

  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:application.properties" />
    <property name="ignoreResourceNotFound" value="true" /> 
    <-- Ignore file not found -->
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <-- Ignore when tokens are not found -->
    
    <!-- Token that separates default values on a placeholder-by-placeholder basis e.g. ${server.name?localhost} -->
    <property name="valueSeparator" value="?" />
                ...
  </bean>

2. Set the default values for your properties

  <bean id="myServer" class="com.gordondickens.myapp.MyServerConfig">
    <property name="serverName" value="${server.name?localhost}" />
    <property name="serverPort" value="${server.port?25}" />
      ...
  </bean>

Notes

  • If unspecified, the default separator is a colon “:”
  • This option is not available when using the “context” namespace – (submitted Jira ticket: SPR-7794)

About Gordon

Technology enthusiast primarily focused on Java and Open Source projects. Spring Certified Professional and Trainer. http://twitter.com/gdickens http://linkedin.com/in/gordondickens http://github.com/gordonad
This entry was posted in Roo, Spring, Spring Framework and tagged , , , . Bookmark the permalink.

5 Responses to Using Default Values for Properties in Spring

  1. Pingback: Tweets that mention Technophile Blog ยป Using Default Values for Properties in Spring -- Topsy.com

  2. Pingback: Spring Default Values – Lessons Learned « Bitlingo

  3. Pingback: Spring Default Values – Lessons Learned

  4. Tarundeep Batra says:

    Very useful !!!

    Thanks
    Tarun

  5. Tarundeep Batra says:

    very useful

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>