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

10

是否有办法在.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)中使用的系统参数。


我认为不会有默认值,因为如果系统属性存在默认定义,则不需要使用 -option。您可以编程设置默认值。 - Mithat Konuk
需要使用核心Java解决方案吗? - Michal
这是什么类型的应用程序?有一些工具包(例如Spring)作为库的一部分提供此功能,但否则您只能定义默认值并自行覆盖它们。 - chrylis -cautiouslyoptimistic-
根据我所读的,有一个 system.c 文件的本地代码,在运行时设置系统属性... - Mithat Konuk
2个回答

0
如果您使用以下命令运行程序: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]);

     }

}

上述代码未加载属性文件,希望你能理解基本思路,祝你好运!


我需要不去修改 main() 函数的参数。 - Jason S

0

创建一个包含默认值的属性文件。此链接展示了如何使用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
  • 注意:命令行中的“-D”后面不应有空格。
  • 注意,myprop.properties可以放置在jar文件中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接