有没有办法在.jar文件中设置Java系统属性,以便它们具有默认值但可以在命令行覆盖?

时间:2016-11-26 18:08:09

标签: java configuration

有没有办法在.jar文件中设置Java系统属性(例如通过JAR清单),以便它们具有默认值但可以在命令行覆盖?

例如,假设我想将系统属性foo.bar设置为haha

 java -jar myprog.jar

会将foo.bar默认为haha,但

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

会将foo.bar设置为hoho

更新:这不应该触及main(String [] args)中使用的系统args。

2 个答案:

答案 0 :(得分:1)

创建包含默认值的属性文件。 This link shows how to work with Java properties files

由于命令行属性已经在您的应用程序的System.properties中可用(例如-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
  • 注意:&#34; -D&#34;之后不应有空格。在命令上 线。
  • 请注意,myprop.properties可以放在jar文件中。

答案 1 :(得分:0)

If you run this using: java -jar myprog.jar foo.bar=hoho typing args[0] inside the main method will return foo.bar=hoho so we need to split it.

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]);

     }

}

The above code doesn't load the property file, I hope you get the basic idea, good luck!