如何在Ant+Java环境下为System Properties参数设置默认值?
为Ant构建的系统属性设置默认值
问题场景
现有Ant的build.xml中定义了endPoint目标,通过<sysproperty>将命令行参数传递给Java程序的sampleClass。当用户未通过-DcommandType=xxx或-DvalueType=xxx传入参数时,Ant会将变量名(如${commandType})直接作为值传递,导致Java程序无法获取预期的默认值。需要实现:用户传入参数时使用指定值,未传入时默认使用TYPE0。
解决方案一:在Ant构建脚本中设置默认值
通过Ant的<property>标签为目标变量定义默认值,Ant会优先使用命令行传入的-D参数值,未传入时则使用默认值。修改后的build.xml代码如下:
<target name="endPoint" depends="standard-release"> <!-- 为commandType和valueType设置默认值TYPE0 --> <property name="commandType" value="TYPE0"/> <property name="valueType" value="TYPE0"/> <java classname="callPath.sampleClass" classpath="${bp:run.classpath}" fork="true"> <sysproperty key="commandType" value="${commandType}"/> <sysproperty key="commandName" value="${Name}"/> <sysproperty key="valueType" value="${valueType}"/> <sysproperty key="valueName" value="${valueName}"/> </java> </target>
原理
Ant的<property>具有不可变性:如果命令行已经通过-D定义了commandType或valueType,<property>标签的默认值不会覆盖它;若未传入,则使用<property>中定义的TYPE0作为变量值,再通过<sysproperty>传递给Java程序。
解决方案二:在Java代码中设置默认值
如果无法修改build.xml,可以在Java代码中调用System.getProperty()时指定默认值,同时处理Ant传递变量名字符串的情况:
public final class sampleClass { public static void main(String[] args) throws Exception { final String commandType = getValidProperty("commandType", "TYPE0"); final String commandName = System.getProperty("commandName"); final String valueType = getValidProperty("valueType", "TYPE0"); final String valueName = System.getProperty("valueName"); // ...后续业务逻辑 } // 处理Ant传入变量名字符串的情况 private static String getValidProperty(String key, String defaultValue) { String value = System.getProperty(key); if (value != null && value.startsWith("${") && value.endsWith("}")) { return defaultValue; } return value != null ? value : defaultValue; } }
说明
新增的getValidProperty方法会判断属性值是否为Ant未解析的变量名格式(如${commandType}),若是则返回默认值TYPE0,确保所有未传入参数的场景都能得到预期结果。
内容的提问来源于stack exchange,提问作者jjl
相关产品推荐
相关产品推荐

