gpt4 book ai didi

java - 从窗口服务运行 jar 应用程序时,在运行时未获取环境变量中用户变量的值?

转载 作者:行者123 更新时间:2023-11-30 06:39:41 25 4
gpt4 key购买 nike

我使用了一个方法“System.getenv();”在 jar 应用程序中获取用户定义的环境变量的值。我已经使 jar 应用程序从窗口服务运行。但是当我尝试启动该服务时,它没有获取用户定义的环境变量的值并显示空指针异常。我试过在“System.getenv(“JAVA_HOME”);”中使用系统变量名称方法,通过获取相应的值可以正常工作。环境变量中的用户变量有什么错误。我应该在代码中做些什么吗?

最佳答案

我确认 Windows 服务默认运行为“本地系统帐户”,不访问用户环境。

您可以使用服务的用户帐户登录。

alt text http://www.adobe.com/devnet/contribute/articles/cps_autodeploy/fig06.gif

但请注意,在您的计算机重新启动之前,您的服务将不知道环境变量 更改! (参见此 Microsoft technote 或此 SO question):

[your service] will inherit its environment from the Services.exe process.
The Services.exe process receives the environment settings for the Local System account when Windows starts.
Because the Services.exe process does not use Windows Messaging, when it receives messages that indicate that a value has changed after Windows starts, the Services.exe process does not update its environment settings.
You cannot force a service that is running to acknowledge a dynamic change to the environment of the Local System account.

这对于 JAVA_HOME(不经常更改)可能不是问题,但对于其他动态设置的环境变量可能是个问题。


如果这成为一个问题(例如,如果您无法使用给定的用户帐户启动您的服务),您可以在您的 Java 程序中嵌入一个run as 命令以查询注册表并获取环境变量的当前值

  String  commands [] = new String [] {
"CMD.EXE",
"/C",
"RUNAS /savecred /user:"
+ username
+ " " + "regedit.exe"
};

Runtime.getRuntime().exec(commands);

with username = 当前连接用户的登录名(如果没有人连接,则需要跳过程序中基于 USER 环境变量的所有部分)

然后您将能够 query the window registry ,直接读取其中存储的“用户变量”(它们保存在 HKEY_CURRENT_USER\Environment 中)。

关于java - 从窗口服务运行 jar 应用程序时,在运行时未获取环境变量中用户变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/536378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com