【问题标题】: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 系统属性,以便它们具有默认值但可以在命令行中覆盖?
【发布时间】:2016-11-26 18:08:08
【问题描述】:

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

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

 java -jar myprog.jar

默认 foo.barhaha 但是

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

会将foo.bar 设置为hoho


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

【问题讨论】:

  • 我认为不会有默认值,因为如果系统属性存在默认定义,则无需采用-option。您可以通过编程方式将其设置为默认值
  • 必须是核心 Java 解决方案吗?
  • 这是什么类型的应用程序?有一些工具包(例如 Spring)提供此功能作为库的一部分,但除此之外,您只能定义默认值并自己覆盖它们。
  • 据我所知,有 system.c 文件本机代码在运行时设置系统属性...

标签: java configuration


【解决方案1】:

如果您使用: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]);

     }

}

上面的代码没有加载属性文件,希望你有基本的思路,祝你好运!

【讨论】:

  • 我不需要触摸 main() 参数。
【解决方案2】:

创建一个包含默认值的属性文件。 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
  • 注意:命令中的“-D”后面不能有空格 行。
  • 注意 myprop.properties 可以放在 jar 文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多