spring @Value 注解的默认值

Default value for spring @Value annotation

我有一个 属性 注释 @Value,通常从 context.xml (jndi/tomcat)

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

这工作正常,但我们安装了我们的软件,其中不应配置 属性。

但是,如果缺少 属性,我会得到一个 javax.naming.NameNotFoundException: Name [some.property] is not bound in this Context. Unable to find [some.property].,这是合乎逻辑的。

我尝试通过这种方式添加默认值来解决此问题:

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

但是,我仍然得到同样的错误。

关于如何 prevent/fix 这个有什么想法吗?

我想在 Spring 3.2.x 和 Spring 4+ 环境中使用它。 注释@Value 可从 Spring 3+

更新: 问题不在于 @Value 注释,而在于 app-config.xml

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

这导致了启动时的错误!

但是,如果我在这里添加default-value="something",它仍然会失败并出现同样的错误

我通过在 属性 占位符和 @value 注释中定义默认值解决了这个问题:

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

和:

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