簡體   English   中英

有沒有辦法在.jar文件中設置Java系統屬性,以便它們具有默認值但可以在命令行覆蓋?

[英]Is there any way to set Java system properties in a .jar file so that they have default values but can be overridden at the command line?

有沒有辦法在.jar文件中設置Java系統屬性(例如通過JAR清單),以便它們具有默認值但可以在命令行覆蓋?

例如,假設我想將系統屬性foo.bar設置為haha

 java -jar myprog.jar

haha會將foo.bar默認為haha

 java -D foo.bar=hoho -jar myprog.jar

foo.bar設置為hoho


更新:這不應該觸及main(String [] args)中使用的系統args。

創建包含默認值的屬性文件。 此鏈接顯示如何使用Java屬性文件

由於命令行屬性已經在應用程序的-Dtest=bart可用(例如-Dtest=bart ),並且由於命令行屬性需要被屬性文件中的屬性覆蓋,因此您可以執行以下操作:

這個簡單的類將從myprop.properties中讀取屬性,並將鍵/值放入System.properties。 如果該屬性已存在於System.properties中,因為在命令行中指定了該屬性,則不會覆蓋該屬性。

package org.snb;

import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

public class PropertiesTester {
    public static void main(String[] args) throws Exception {
        InputStream in = PropertiesTester.class.getClassLoader().getResourceAsStream("myprop.properties");

        Properties defaultProperties = new Properties();
        defaultProperties.load(in);

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

        for (Map.Entry<Object,Object> e : System.getProperties().entrySet()) {
            System.out.println("key: " + e.getKey() + " value: " + e.getValue());
        }
        in.close();
    }
}

// myprop.properties

test=maggie
myval=homer
no-override=krusty

命令行應包括:

-Dtest=bart -Dtest2=trump
  • 注意:命令行上的“-D”后面不應有空格。
  • 請注意,myprop.properties可以放在jar文件中。

如果你使用以下命令運行: java -jar myprog.jar foo.bar=hoho在main方法中鍵入args[0]將返回foo.bar=hoho所以我們需要拆分它。

public static void main(String[] args) {

     if(args[0].isEmpty) { // no first argument, so we will use the default value
          prop.setProperty("foo.bar", "haha");
     } else {

         String[] words = args[0].split("="); // split the argument where the = is
         prop.setProperty(words[0], words[1]);

     }

}

上面的代碼沒有加載屬性文件,希望你得到基本的想法,祝你好運!

暫無
暫無

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

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