使用過Spring Boot,我們都知道通過java -jar可以快速啟動Spring Boot項目。同時,也可以通過在執行jar -jar時傳遞參數來進行配置。本文帶大家系統的了解一下Spring Boot命令行參數相關的功能及相關源碼分析。
命令行參數使用
啟動Spring Boot項目時,我們可以通過如下方式傳遞參數:
java -jar xxx.jar --server.port=8081
默認情況下Spring Boot使用8080端口,通過上述參數將其修改為8081端口,而且通過命令行傳遞的參數具有更高的優先級,會覆蓋同名的其他配置參數。
啟動Spring Boot項目時傳遞參數,有三種參數形式:
- 選項參數
- 非選項參數
- 系統參數
選項參數,上面的示例便是選項參數的使用方法,通過“–-server.port”來設置應用程序的端口。基本格式為“--name=value”(“--”為連續兩個減號)。其配置作用等價於在application.properties中配置的server.port=8081。
非選項參數的使用示例如下:
java -jar xxx.jar abc def
上述示例中,“abc”和“def”便是非選項參數。
系統參數,該參數會被設置到系統變量中,使用示例如下:
java -jar -Dserver.port=8081 xxx.jar
參數值的獲取
選項參數和非選項參數均可以通過ApplicationArguments接口獲取,具體獲取方法直接在使用參數的類中注入該接口即可。
@RestController
public class ArgumentsController {
@Resource
private ApplicationArguments arguments;
}
通過ApplicationArguments接口提供的方法即可獲得對應的參數。關於該接口后面會詳細講解。
另外,選項參數,也可以直接通過@Value在類中獲取,如下:
@RestController
public class ParamController {
@Value("${server.port}")
private String serverPort;
}
系統參數可以通過java.lang.System提供的方法獲取:
String systemServerPort = System.getProperty("server.port");
參數值的區別
關於參數值區別,重點看選項參數和系統參數。通過上面的示例我們已經發現使用選項參數時,參數在命令中是位於xxx.jar之后傳遞的,而系統參數是緊隨java -jar之后。
如果不按照該順序進行執行,比如使用如下方式使用選項參數:
java -jar --server.port=8081 xxx.jar
則會拋出如下異常:
Unrecognized option: --server.port=8081
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
如果將系統參數放在jar包后面,問題會更嚴重。會出現可以正常啟動,但參數無法生效。這也是為什么有時候明明傳遞了參數但是卻未生效,那很可能是因為把參數的位置寫錯了。
這個錯誤是最坑的,所以一定謹記:通過-D傳遞系統參數時,務必放置在待執行的jar包之前。
另外一個重要的不同是:通過@Value形式可以獲得系統參數和選項參數,但通過System.getProperty方法只能獲得系統參數。
ApplicationArguments解析
上面提到了可以通過注入ApplicationArguments接口獲得相關參數,下面看一下具體的使用示例:
@RestController
public class ArgumentsController {
@Resource
private ApplicationArguments arguments;
@GetMapping("/args")
public String getArgs() {
System.out.println("# 非選項參數數量: " + arguments.getNonOptionArgs().size());
System.out.println("# 選項參數數量: " + arguments.getOptionNames().size());
System.out.println("# 非選項具體參數:");
arguments.getNonOptionArgs().forEach(System.out::println);
System.out.println("# 選項參數具體參數:");
arguments.getOptionNames().forEach(optionName -> {
System.out.println("--" + optionName + "=" + arguments.getOptionValues(optionName));
});
return "success";
}
}
通過注入ApplicationArguments接口,然后在方法中調用該接口的方法即可獲得對應的參數信息。
ApplicationArguments接口中封裝了啟動時原始參數的數組、選項參數的列表、非選項參數的列表以及選項參數獲得和檢驗。相關源碼如下:
public interface ApplicationArguments {
/**
* 原始參數數組(未經過處理的參數)
*/
String[] getSourceArgs();
/**
* 選項參數名稱
*/
Set<String> getOptionNames();
/**
* 根據名稱校驗是否包含選項參數
*/
boolean containsOption(String name);
/**
* 根據名稱獲得選項參數
*/
List<String> getOptionValues(String name);
/**
* 獲取非選項參數列表
*/
List<String> getNonOptionArgs();
}
命令行參數的解析
上面直接使用了ApplicationArguments的注入和方法,那么它的對象是何時被創建,何時被注入Spring容器的?
在執行SpringApplication的run方法的過程中會獲得傳入的參數,並封裝為ApplicationArguments對象。相關源代碼如下:
public ConfigurableApplicationContext run(String... args) {
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// ...
prepareContext(context, environment, listeners, // ...
} catch (Throwable ex) {
// ...
}
return context;
}
在上述代碼中,通過創建一個它的實現類DefaultApplicationArguments來完成命令行參數的解析。
DefaultApplicationArguments部分代碼如下:
public class DefaultApplicationArguments implements ApplicationArguments {
private final Source source;
private final String[] args;
public DefaultApplicationArguments(String... args) {
Assert.notNull(args, "Args must not be null");
this.source = new Source(args);
this.args = args;
}
// ...
@Override
public List<String> getOptionValues(String name) {
List<String> values = this.source.getOptionValues(name);
return (values != null) ? Collections.unmodifiableList(values) : null;
}
private static class Source extends SimpleCommandLinePropertySource {
Source(String[] args) {
super(args);
}
// ...
}
}
通過構造方法,將args賦值給成員變量args,其中接口ApplicationArguments中getSourceArgs方法的實現在該類中便是返回args值。
針對成員變量Source(內部類)的設置,在創建Source對象時調用了其父類SimpleCommandLinePropertySource的構造方法:
public SimpleCommandLinePropertySource(String... args) {
super(new SimpleCommandLineArgsParser().parse(args));
}
在該方法中創建了真正的解析器SimpleCommandLineArgsParser並調用其parse方法對參數進行解析。
class SimpleCommandLineArgsParser {
public CommandLineArgs parse(String... args) {
CommandLineArgs commandLineArgs = new CommandLineArgs();
for (String arg : args) {
// --開頭的選參數解析
if (arg.startsWith("--")) {
// 獲得key=value或key值
String optionText = arg.substring(2, arg.length());
String optionName;
String optionValue = null;
// 如果是key=value格式則進行解析
if (optionText.contains("=")) {
optionName = optionText.substring(0, optionText.indexOf('='));
optionValue = optionText.substring(optionText.indexOf('=')+1, optionText.length());
} else {
// 如果是僅有key(--foo)則獲取其值
optionName = optionText;
}
// 如果optionName為空或者optionValue不為空但optionName為空則拋出異常
if (optionName.isEmpty() || (optionValue != null && optionValue.isEmpty())) {
throw new IllegalArgumentException("Invalid argument syntax: " + arg);
}
// 封裝入CommandLineArgs
commandLineArgs.addOptionArg(optionName, optionValue);
} else {
commandLineArgs.addNonOptionArg(arg);
}
}
return commandLineArgs;
}
}
上述解析規則比較簡單,就是根據“--”和“=”來區分和解析不同的參數類型。
通過上面的方法創建了ApplicationArguments的實現類的對象,但此刻還並未注入Spring容器,注入Spring容器是依舊是通過上述SpringApplication#run方法中調用的prepareContext方法來完成的。相關代碼如下:
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
// ...
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 通過beanFactory將ApplicationArguments的對象注入Spring容器
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
// ...
}
至此關於Spring Boot中ApplicationArguments的相關源碼解析完成。
原文鏈接:《Spring Boot啟動命令參數詳解及源碼分析》
Spring技術視頻
CSDN學院:《Spring Boot 視頻教程全家桶》
