1. 程式人生 > 程式設計 >SPRING BOOT啟動命令引數及原始碼詳析

SPRING BOOT啟動命令引數及原始碼詳析

前言

使用過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的相關原始碼解析完成。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。