SpringBoot源码阅读(6)——命令行参数处理

代码位置

SpringApplication类的实例方法run方法,第300行

ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);

相关类

  • ApplicationArguments
  • DefaultApplicationArguments
  • Source
  • SimpleCommandLinePropertySource
  • SimpleCommandLineArgsParser

解析

public SimpleCommandLinePropertySource(String... args) {
	super(new SimpleCommandLineArgsParser().parse(args));
}
public CommandLineArgs parse(String... args) {
		CommandLineArgs commandLineArgs = new CommandLineArgs();
	for (String arg : args) {
		if (arg.startsWith("--")) {
			String optionText = arg.substring(2);
			String optionName;
			String optionValue = null;
			int indexOfEqualsSign = optionText.indexOf('=');
			if (indexOfEqualsSign > -1) {
				optionName = optionText.substring(0, indexOfEqualsSign);
				optionValue = optionText.substring(indexOfEqualsSign + 1);
			}
			else {
				optionName = optionText;
			}
			if (optionName.isEmpty()) {
				throw new IllegalArgumentException("Invalid argument syntax: " + arg);
			}
			commandLineArgs.addOptionArg(optionName, optionValue);
		}
		else {
			commandLineArgs.addNonOptionArg(arg);
		}
	}
	return commandLineArgs;
}

主要逻辑:
命令行参数分为两种参数:选项参数非选项参数

选项参数特点:以--开头,中间可以有=,也可以没有
不以--开头的就是非选项参数

比如:--foo=value 会解析为选项参数,参数名为foo,参数值为value
但是如果写成了--=或者只有--,就会抛出异常。

最后参数放入了CommandLineArgs类的实例之中。
CommandLineArgs再被放入Source中,参数名是commandLineArgs

Source的类结构
继承:

  • SimpleCommandLinePropertySource
  • CommandLinePropertySource
  • EnumerablePropertySource
  • PropertySource
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值