2017-09-05 32 views
1

替換屬性文件佔位符我想有一個動態的佔位符我的屬性文件使用通過VM參數(-D PARAMS)彈簧4

我application.properties文件

性能

property.first=${some-value} (placeholder in property file) 

我想用通過VM參數say -Dsome-value=12傳遞的值替換上面的佔位符($ {some-value})。

其實我可以通過@Value註釋在spring引導中實現它,但我使用的是xml配置的spring 4。在ApplicationContext.xml文件中添加任何xml配置是否有任何解決方案(我不想更改java代碼)

回答

1

讀取Properties對象中的.properties文件,然後用通過VM參數傳遞的值替換佔位符:

public static boolean replaceVariables(Properties properties) { 
     boolean changed = false; 
     for (Entry<Object, Object> entry : properties.entrySet()) { 
      if (entry.getValue() instanceof String) { 
       String value = (String) entry.getValue(); 
       value = value.trim(); 
       if (value.startsWith("${") && value.endsWith("}")) { 
        value = System.getProperty(value.substring(2, value.length() - 1)); 
        if (value == null) 
         entry.setValue(""); 
        else 
         entry.setValue(value); 
        changed = true; 
       } 
      } 
     } 
     return changed; 
    } 
+0

謝謝你這樣做,但是當我從另一個類訪問相同的屬性它仍然給我相同的舊值 – Rakesh