0

我已经使用 install4j 创建了一个 Windows 服务,一切正常,但现在我需要将命令行参数传递给该服务。我知道我可以在新服务向导的服务创建时配置它们,但我希望将参数传递给注册服务命令,即:

myservice.exe --install --arg arg1=val1 --arg arg1=val2 "My Service Name1"

或将它们放入 .vmoptions 文件中,例如:

-Xmx256m
arg1=val1
arg2=val2

似乎这样做的唯一方法是修改我的代码以通过 exe4j.launchName 获取服务名称,然后加载具有该特定服务必要配置的其他文件或环境变量。我过去使用过其他的 java 服务创建工具,它们都直接支持用户注册的命令行参数。

4

1 回答 1

1

我知道你在一月份问过这个问题,但你有想过这个吗?

我不知道你从哪里采购 val1、val2 等。它们是否由用户在安装过程中输入到表单中的字段中?假设他们是,那么这与我不久前遇到的问题类似。

我的方法是拥有一个带有必要字段(作为文本字段对象)的可配置表单,并且显然将变量分配给文本字段的值(在文本字段的“用户输入/变量名称”类别下)。

在安装过程的后期,我有一个显示进度屏幕,上面附有一个运行脚本操作,并带有一些 java 来实现我想要做的事情。

以这种方式在 install4j 中选择设置变量时有两个“陷阱”。首先,无论如何都必须设置变量,即使它只是空字符串。因此,如果用户将字段留空(即他们不想将该参数传递给服务),您仍然需要为 Run 可执行文件或 Launch Service 任务提供一个空字符串(稍后会详细介绍) 其次,参数不能有空格——每个以空格分隔的参数都必须有自己的行。

考虑到这一点,这里有一个运行脚本代码片段,可以实现您想要的:

final String[] argumentNames = {"arg1", "arg2", "arg3"};
// For each argument this method creates two variables. For example for arg1 it creates
// arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional.
// If the value of the variable set from the previous form (in this case, arg1) is not empty, then it will
// set 'arg1ArgumentIdentifierOptional' to '--arg', and 'arg1ArgumentAssignmentOptional' to the string arg1=val1 (where val1 
// was the value the user entered in the form for the variable).
// Otherwise, both arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional will be set to empty.
//
// This allows the installer to pass both parameters in a later Run executable task without worrying about if they're
// set or not.

for (String argumentName : argumentNames) {
    String argumentValue = context.getVariable(argumentName)==null?null:context.getVariable(argumentName)+"";
    boolean valueNonEmpty = (argumentValue != null && argumentValue.length() > 0);
    context.setVariable(
       argumentName + "ArgumentIdentifierOptional",
       valueNonEmpty ? "--arg": ""
    );
    context.setVariable(
       argumentName + "ArgumentAssignmentOptional",
       valueNonEmpty ? argumentName+"="+argumentValue : ""
    );    
}

return true;

最后一步是启动服务或可执行文件。我不太确定服务是如何工作的,但是使用可执行文件,您可以创建任务,然后编辑“参数”字段,为其提供以行分隔的值列表。

所以在你的情况下,它可能看起来像这样:

--install
${installer:arg1ArgumentIdentifierOptional}
${installer:arg1ArgumentAssignmentOptional}
${installer:arg2ArgumentIdentifierOptional}
${installer:arg2ArgumentAssignmentOptional}
${installer:arg3ArgumentIdentifierOptional}
${installer:arg3ArgumentAssignmentOptional}

“我的服务名称1”

就是这样。如果其他人知道如何更好地做到这一点,请随时改进此方法(这是针对 install4j 4.2.8,顺便说一句)。

于 2012-07-10T00:42:23.317 回答