簡體   English   中英

如何從Spring中的JVM選項訪問屬性值,並在applicationContext.xml中設置一些默認值?

[英]How to access property value from JVM options in Spring with some default values set in applicationContext.xml?

我想訪問Spring的applicationContext.xml中從JVM傳遞的一些屬性值。 根據Spring的表達式語言功能,我知道實現此目的的一種方法是#{systemProperties.myProperty} -DmyProperty=xyz #{systemProperties.myProperty}用於某些-DmyProperty=xyz

但我感興趣的是,如果用戶沒有從服務器的JVM選項設置值,我通過JVM分配的每個這樣的屬性都有一個默認值。 如何在Spring的任何上下文xml文件中實現此目的? 請幫忙。

您可以創建一個bean,它使用默認值從上下文中獲取map參數並初始化系統屬性

<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之前,以便首先初始化屬性

UPDATE

這是關於覆蓋系統屬性。 但是如果你只需要像這里一樣覆蓋Spring占位符

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

將property-placeholder的local-override attr設置為“true”就足夠了

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

在Spring EL中,您可以添加默認值。 在你的情況下:

#{systemProperties.myProperty:MyDefaultValue}

使用基於注釋的配置,您可以使用Elvis運算符在Spring EL中提供默認值:

 @Value("#{systemProperties['hostname'] ?: 'default-hostname'}")
 private String hostname;

基於atrain的有用答案。 我還不能評論,或者我已經在那里進行了語法修正:(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM