Search code examples
springpropertiesannotationsjndidefault-value

Default value for spring @Value annotation


I have a property annotated with @Value, normally populated from context.xml (jndi/tomcat)

@Value("${some.property}")
private String property

This works fine, but we have installations of our software, where that property shouldn't be configured.

However, if the property is missing, I get a javax.naming.NameNotFoundException: Name [some.property] is not bound in this Context. Unable to find [some.property]., which is logical.

I tried fixing this, by adding a default value this way:

@Value("${some.property:some_property_not_configured}")
private String property

However, I still get the same error.

Any ideas how to prevent/fix this?

I would like to use this in a Spring 3.2.x and a Spring 4+ environment. The annotation @Value is available from Spring 3+

UPDATE: The problem was not with the @Value annotation, but in app-config.xml

<entry key="some.property">
    <jee:jndi-lookup jndi-name="java:comp/env/some.property" />
</entry>

This caused the error at startup time!

However, if I add default-value="something" here, it still fails with the same error


Solution

  • I solved this by defining a default value in the property-placeholder AND in the @value annotation:

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties">
            <bean class="java.util.Properties">
                <constructor-arg>
                    <map>
                        <entry key="some.property">
                            <jee:jndi-lookup jndi-name="java:comp/env/some.property" default-value="not_configured" />
                        </entry>
                    </map>
                </constructor-arg>
            </bean>
        </property>
    </bean>
    

    and:

    @Value(value = "${some.property:not_configured}")
    private String property;