Java 系统环境变量

2022-01-16 00:00:00 environment-variables java

Java 是否有一个默认的系统环境变量,当我们设置它时总是会被读取/附加?CATALINA_OTPS/JAVA_OPTS 等似乎只适用于 TOMCAT/JBOSS 等.

Does Java have a default System Environment Variable that will always be read/appended when we set it? CATALINA_OTPS/JAVA_OPTS etc seems only for TOMCAT/JBOSS etc.

  1. 我不想通过 Java 系统属性(通过 -Dprop1=value1 -Dprop2=value2 传入)设置它,因为它涉及 shell/batch 脚本.
  2. 它应该可以跨操作系统工作,就像在 Windows 中双击 jar 文件一样.
  3. 它应该适用于不同的 JRE(Sun、IBM、OpenJDK 等).
  4. 不应涉及额外的编码.
  5. 它应该可以在大多数库配置文件中使用,例如设置 log4j级别 ${LOG_LEVEL}.

更新:添加了第 4 项和第 5 项.从标题中删除 OS 以使我的问题更清楚.

Update: Added item # 4 and 5. Remove OS from title to make my question clearer.

Update 2:看了 Perception 的回答后,我的第 2 和第 3 项似乎可以通过 System.getenv 实现.第4、5项如何实现?

Update 2: After looking at Perception's answer, it seems like my item 2 and 3 can be achieved via System.getenv. How to achieve item 4 and 5?

以下是场景示例:现在想象一下,JAVA_DEFAULT_OPTS 是一个环境变量,Java 将读取它,因为它现在已成为标准.在开发台式机上,我设置 JAVA_DEFAULT_OPTS=-DLOG_LEVEL=DEBUG -Xmx384m;在生产服务器机器上,客户设置 JAVA_DEFAULT_OPTS=-DLOG_LEVEL=INFO -Xmx1024m.当我/用户在 Windows 上双击 jar 文件时,应用程序将运行不同的 log4j 级别和最大内存堆大小.

Here is example of scenario: Imagine now JAVA_DEFAULT_OPTS is an environment variable that will be read by Java as it has now become the standard. On development desktop machine, I set JAVA_DEFAULT_OPTS=-DLOG_LEVEL=DEBUG -Xmx384m; On production server machine, customers set JAVA_DEFAULT_OPTS=-DLOG_LEVEL=INFO -Xmx1024m. When I/users double click the jar file on Windows, the application will run will different log4j level and max memory heap size.

推荐答案

有一个特殊的环境变量叫做_JAVA_OPTIONS,它的值会被JVM(java.exe)拾取.

There is a special environment variable called _JAVA_OPTIONS, its value will be picked up by the JVM (java.exe).

在 Windows 中:

In Windows:

set _JAVA_OPTIONS=-Xms64m -Xmx128m -Dawt.useSystemAAFontSettings=lcd

在 Linux 中:

export _JAVA_OPTIONS='-Xms64m -Xmx128m -Dawt.useSystemAAFontSettings=lcd'

对于 Java Web Start,它是 JAVAWS_VM_ARGS.对于 javaw.exe (Applet),它是 _JPI_VM_OPTIONS.

For Java Web Start it's JAVAWS_VM_ARGS. For javaw.exe (Applet), it's _JPI_VM_OPTIONS.

编辑 20201213

_JAVA_OPTIONS 环境变量没问题,但没有记录或支持.

_JAVA_OPTIONS environment variable was ok but was not documented or supported.

由于没有标准化,其他供应商都有自己的名称,例如IBM_JAVA_OPTIONS.按照惯例,前导下划线名称是私有的,因此标准化 _JAVA_OPTIONS 的使用并不是一个好主意.

Since it is not standardized, other vendors have their own names e.g. IBM_JAVA_OPTIONS. Leading underscore names are private by convention so it's not a good idea to standardize the usage of _JAVA_OPTIONS.

这就是为什么 JAVA_TOOL_OPTIONS 应该是首选的原因.

That's why JAVA_TOOL_OPTIONS should be the preferred choice.

参考:https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#tooloptions

相关文章