Announcement Announcement Module
No announcement yet.
Default Values for Configuration with @Value Page Title Module
Move Remove Collapse
Conversation Detail Module
  • 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
    It is referenced in the Spring configuration with
    <util:properties id="props" location="" />
    In my central Config class I use the @Value-Annotation to reference these properties:

    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

    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 "" 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...


    • #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


      • #4
        A more simple solution

        A very simple solution is to use the following syntax: