Announcement Announcement Module
Collapse
No announcement yet.
Default Values for Configuration with @Value Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Default Values for Configuration with @Value

    I have tried to use the new @Value-Annotation of Spring 3.0 to configure the application.

    My config file has some properties like
    Code:
    month=2010-02
    #start_date=2009-12-01
    #end_date=2009-12-31
    ...
    It is referenced in the Spring configuration with
    Code:
    <util:properties id="props" location="file:application.properties" />
    In my central Config class I use the @Value-Annotation to reference these properties:

    Code:
    private @Value("#{props.month}") String month;
    
    private @Value("#{props.end_date}") String sEndDate;
    
    private @Value("#{props.start_date}") String sStartDate;
    As you can see above, the property month is set in the configuration file, start_date and end_date are commented out. They are only neccessary if month is not set.

    If I set every property (remove the #) everything is fine. If I start the application with the mentioned configuration I get an exception:
    EL1008E: (pos 6): Field or property 'end_date' cannot be found on object of type 'java.util.Properties'

    OK, Properties return null if a key is not set. But I think this should not produce an Exception... The PropertyPlaceholderConfigurer can be configured to ignore not existing properties. Is there a possibility to define a default value or ignore properties that are not set with @Value?

  • #2
    I found out that one can write

    Code:
    private @Value("#{props['end_date']}") String sEndDate;
    instead. The bean props is of type java.util.Properties so one can access the properties as attributes using "props.foo" or the "map-way" using "props['foo']". The first one throws an exception if the property is missing because it interprets it as missing attribute. The last one simply ignores it...

    Comment


    • #3
      With SPEL you can do slightly more complex conditional logic as well.
      eg. in your case - use end date if month is not null

      Comment


      • #4
        A more simple solution

        A very simple solution is to use the following syntax:

        ${propertyName:default}

        Comment

        Working...
        X