如何在Spring中通过JVM选项访问属性值,并在applicationContext.xml中设置一些默认值?

4

我希望能够在Spring的applicationContext.xml中访问从JVM传递的一些属性值。我知道实现这个的一种方式是使用Spring表达式语言特性中的#{systemProperties.myProperty},对应于一些-DmyProperty=xyz

但是,我想为每个通过JVM分配的属性设置一个默认值,以防用户没有从服务器的JVM选项中设置该值。我如何在任何Spring上下文xml文件中实现此目的呢?请帮忙。


看看我的更新,也许会引起你的兴趣。 - Evgeniy Dorofeev
3个回答

3
您可以创建一个bean,该bean从上下文中获取带有默认值的映射参数,并初始化系统属性。
<bean class="test.B1">
    <constructor-arg>
        <map>
            <entry key="p1" value="v1" />
            <entry key="p2" value="v2" />
                                 ....
        </map>
    </constructor-arg>
</bean>

.

public B1(Map<String, String> defaultProperties) {
    for (Map.Entry<String, String> e : defaultProperties.entrySet()) {
        if (System.getProperty(e.getKey()) == null) {
            System.setProperty(e.getKey()
                    , e.getValue());
        }
    }
}

在上下文中,B1的定义应该在任何使用#{systemProperties.myProperty}的bean之前,以便先初始化属性。

更新

这是关于覆盖系统属性的内容。但如果您只需要覆盖Spring占位符,就像这里一样:

<bean class="test.B1">
    <property name="prop1" value="${xxx}" />
</bean>

只需要将property-placeholder的local-override属性设置为"true"即可。

<context:property-placeholder location="classpath:/app.properties" local-override="true" />

1
在Spring EL中,您可以添加默认值。在您的情况下:
#{systemProperties.myProperty:MyDefaultValue}

尝试过了,但这里出现了表达式语言解析错误。我想这可能是在Spring属性占位符中使用${x.y}导致的。 - Atharva

1
使用基于注解的配置,您可以在Spring EL中使用Elvis运算符提供默认值:
 @Value("#{systemProperties['hostname'] ?: 'default-hostname'}")
 private String hostname;

基于atrain的有用回答。我目前还不能评论,否则我会在那里放置语法更正 :(


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接