是否有办法在.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)中使用的系统参数。
是否有办法在.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)中使用的系统参数。
java -jar myprog.jar foo.bar=hoho
,则在主方法中键入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]);
}
}
上述代码未加载属性文件,希望你能理解基本思路,祝你好运!
创建一个包含默认值的属性文件。此链接展示了如何使用Java属性文件。
由于命令行属性已经在应用程序的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();
}
}
// 我的属性文件
test=maggie
myval=homer
no-override=krusty
命令行应包含:
-Dtest=bart -Dtest2=trump