设置多个系统属性 Java 命令行

是否有更简单的方法在命令行上为 Java 程序指定多个 System Properties,而不是使用多个 D 语句?

尽量避免这种情况:

 java -jar -DNAME="myName" -DVERSION="1.0" -DLOCATION="home" program.jar

我想我已经看到了一个例子,有人使用一个 -D和一些引号字符串后,但我不能找到的例子再次。

189606 次浏览

There's nothing on the Documentation that mentions about anything like that.

Here's a quote:

-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:

java -Dfoo="some string" SomeClass

Instead of passing the properties as an argument, you may use a .properties for storing them.

Answer is NO. You might have seen an example where somebody would have set something like :

-DArguments=a=1,b=2,c=3,d=4,e=cow

Then the application would parse value of Arguments property string to get individual values. In your main you can get the key values as(Assuming input format is guaranteed):

String line = System.getProperty("Arguments");
if(line != null) {
String str[] = line.split(",");
for(int i=1;i<str.length;i++){
String arr[] = str[i].split("=");
System.out.println("Key = " + arr[0]);
System.out.println("Value = " +  arr[1]);
}
}

Also, the -D should be before the main class or the jar file in the java command line. Example : java -DArguments=a=1,b=2,c=3,d=4,e=cow MainClass

If the required properties need to set in system then there is no option than -D But if you need those properties while bootstrapping an application then loading properties through the properties files is a best option. It will not require to change build for a single property.

You may be able to use the JAVA_TOOL_OPTIONS environment variable to set options. It worked for me with Rasbian. See Environment Variables and System Properties which has this to say:

In many environments, the command line is not readily accessible to start the application with the necessary command-line options.

This often happens with applications that use embedded VMs (meaning they use the Java Native Interface (JNI) Invocation API to start the VM), or where the startup is deeply nested in scripts. In these environments the JAVA_TOOL_OPTIONS environment variable can be useful to augment a command line.

When this environment variable is set, the JNI_CreateJavaVM function (in the JNI Invocation API), the JNI_CreateJavaVM function adds the value of the environment variable to the options supplied in its JavaVMInitArgs argument.

However this environment variable use may be disabled for security reasons.

In some cases, this option is disabled for security reasons. For example, on the Oracle Solaris operating system, this option is disabled when the effective user or group ID differs from the real ID.

See this example showing the difference between specifying on the command line versus using the JAVA_TOOL_OPTIONS environment variable.

screenshot showing use of JAVA_TOOL_OPTIONS environment variable