由 JOpt OptionSet 支持的 CommandLinePropertySource 实现。
针对提供给 main 方法的参数 String[] 配置和执行 OptionParser,并使用生成的 OptionSet 对象创建JOptCommandLinePropertySource:
public static void main(String[] args) {
OptionParser parser = new OptionParser();
parser.accepts("option1");
parser.accepts("option2").withRequiredArg();
OptionSet options = parser.parse(args);
PropertySource ps = new JOptCommandLinePropertySource(options);
// ...
}演示 JOptCommandLinePropertySource 类的基础用法。代码如下:
package com.springframework.core.env;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.springframework.core.env.JOptCommandLinePropertySource;
/**
* 测试 JOptCommandLinePropertySource 类
*/
public class JOptCommandLinePropertySourceTest {
public static void main(String[] args) {
String[] argsData = {
"--name=ZhangSan",
"--sex=male",
"--age",
"--message=hello world",
"/images/2020/10/10/face.img",
"ChengDu"
};
OptionParser parser = new OptionParser();
parser.accepts("name").withRequiredArg();
parser.accepts("sex").withOptionalArg();
parser.accepts("age").withRequiredArg();
parser.accepts("message").withRequiredArg();
OptionSet options = parser.parse(argsData);
JOptCommandLinePropertySource ps = new JOptCommandLinePropertySource(options);
// 获取选项名称
System.out.println("获取选项名称:");
for(String optName : ps.getPropertyNames()) {
System.out.println(optName + "=" + ps.getOptionValues(optName));
}
}
}其中:
withRequiredArg():通知选项解析器此构建器的选项需要参数。
withOptionalArg():通知选项解析器此构建器的选项接受可选参数。
如果我们将 main 的参数修改为如下:
String[] argsData = {
"--name",
"--sex=male",
"--age",
"--message=hello world",
"/images/2020/10/10/face.img",
"ChengDu"
};使用 withRequiredArg() 方法修饰参数,例如:parser.accepts("name").withRequiredArg(),运行程序输出结果如下:
获取选项名称: name=[--sex=male] age=[--message=hello world]
上面提供的参数中,--name 没有提供值,但是我们使用了 withRequiredArg() 方法修饰,导致 JOpt 将第二行当做了参数值。
如果使用 withOptionalArg() 方法修饰参数,例如:parser.accepts("name").withOptionalArg(),运行程序输出结果如下:
获取选项名称: name=[] sex=[male] age=[--message=hello world]
上面结果中,name 选项参数因为没有传递值,因此返回空列表。
注意:每个参数后面需要使用 withRequiredArg() 或 withOptionalArg() 修饰,否则不能获取到值。例如:
package com.springframework.core.env;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.springframework.core.env.JOptCommandLinePropertySource;
/**
* 测试 JOptCommandLinePropertySource 类
*/
public class JOptCommandLinePropertySourceTest2 {
public static void main(String[] args) {
String[] argsData = {
"--name=ZhangSan",
"--sex=male",
"--age",
"--message=hello world",
"/images/2020/10/10/face.img",
"ChengDu"
};
OptionParser parser = new OptionParser();
parser.accepts("name").withOptionalArg();
parser.accepts("sex");
parser.accepts("age");
parser.accepts("message");
OptionSet options = parser.parse(argsData);
JOptCommandLinePropertySource ps = new JOptCommandLinePropertySource(options);
// 获取选项名称
System.out.println("获取选项名称:");
for(String optName : ps.getPropertyNames()) {
System.out.println(optName + "=" + ps.getOptionValues(optName));
}
}
}运行上面代码,输出结果如下:
获取选项名称: name=[ZhangSan] sex=[] age=[] message=[]