springboot源碼走讀之二----命令行參數(shù)封裝與上下文環(huán)境準(zhǔn)備

前言

本文主要是接上文源碼走讀之一

  try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
            configureIgnoreBeanInfo(environment);
            Banner printedBanner = printBanner(environment);
            context = createApplicationContext();
            exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                    new Class[] { ConfigurableApplicationContext.class }, context);
            prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            refreshContext(context);
            afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
            }
            listeners.started(context);
            callRunners(context, applicationArguments);
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, listeners);
            throw new IllegalStateException(ex);
        }

這段代碼而來。主要走讀

ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);

這兩步代碼。
首先來看第一步,參數(shù)封裝。

ApplicationArguments生成

ApplicationArguments的主要處理邏輯在于SimpleCommandLineArgsParserparse方法。方法實現(xiàn)如下:

public CommandLineArgs parse(String... args) {
        CommandLineArgs commandLineArgs = new CommandLineArgs();
        for (String arg : args) {
            if (arg.startsWith("--")) {
                String optionText = arg.substring(2, arg.length());
                String optionName;
                String optionValue = null;
                if (optionText.contains("=")) {
                    optionName = optionText.substring(0, optionText.indexOf('='));
                    optionValue = optionText.substring(optionText.indexOf('=')+1, optionText.length());
                }
                else {
                    optionName = optionText;
                }
                if (optionName.isEmpty() || (optionValue != null && optionValue.isEmpty())) {
                    throw new IllegalArgumentException("Invalid argument syntax: " + arg);
                }
                commandLineArgs.addOptionArg(optionName, optionValue);
            }
            else {
                commandLineArgs.addNonOptionArg(arg);
            }
        }
        return commandLineArgs;
    }

這里springboot命令行參數(shù)包括兩種,一種是以--開頭的參數(shù),類似key/value形式的。如--profile,--log.level等。一種是直接以value形式的,如foo等。具體參數(shù)的意義,跟業(yè)務(wù)相關(guān)。

最后這個commandLineArgs被放到什么地方了呢?看如下代碼:

public DefaultApplicationArguments(String... args) {
        Assert.notNull(args, "Args must not be null");
        this.source = new Source(args);
        this.args = args;
    }

我們進一步進入Source中,找到如下代碼:

public PropertySource(String name, T source) {
        Assert.hasText(name, "Property source name must contain at least one character");
        Assert.notNull(source, "Property source must not be null");
        this.name = name;
        this.source = source;
    }

這里初始化一個PropertySource,name為:commandLineArgs,value就為上面初始化的CommandLineArgs。
這里,只要業(yè)務(wù)能獲取到applicationArguments,就能獲取到我們從命令行中傳入的參數(shù)。
通常,我們會通過environment來獲取參數(shù)。例子如下:

 ApplicationContext ctx = SpringApplication.run(StudyApplication.class);
 System.out.println(ctx.getEnvironment().getProperty("foo"));

這里就會在控制臺中打印出key為“foo”的值。那么,environment是如何構(gòu)造的呢?這就到了接下來要看的代碼中了,即environment的構(gòu)造。

Environment的構(gòu)造

Environment的主要代碼如下:

private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
            ApplicationArguments applicationArguments) {
        // Create and configure the environment
        // 創(chuàng)建一個environment對象。如果是`SERVLET`,則new一個StandardServletEnvironment,如果是`REACTIVE`,則new一個StandardReactiveWebEnvironment,否則初始化一個StandardEnvironment。初始化對象的時候,創(chuàng)建一些java標(biāo)準(zhǔn)的環(huán)境參數(shù),如`systemEnvironment`和`systemProperties`及對應(yīng)容器特有的環(huán)境參數(shù),如`servletConfigInitParams`和`servletContextInitParams`
        ConfigurableEnvironment environment = getOrCreateEnvironment();
//該步驟為設(shè)置一些默認(rèn)的converter和formatter及設(shè)置命令行參數(shù)到environment中,還有設(shè)置應(yīng)用程序中設(shè)置的profile及active profile。
        configureEnvironment(environment, applicationArguments.getSourceArgs());
//配置configurationProperties的值
        ConfigurationPropertySources.attach(environment);
//觸發(fā)環(huán)境準(zhǔn)備完成事件,事件的消費者在springboot的代碼中,有如下地方:
// FileEncodingApplicationListener,AnsiOutputApplicationListener,ConfigFileApplicationListener【重要,加載配置文件的地方,下面會專門講】,LoggingApplicationListener 日志系統(tǒng),WebEnvironmentPropertySourceInitializer
        listeners.environmentPrepared(environment);
//綁定環(huán)境到springapplication上。spring.main配置【具體作用,以后用到的時候在做說明】
        bindToSpringApplication(environment);
              //如果不是自定義環(huán)境,則轉(zhuǎn)換之。
        if (!this.isCustomEnvironment) {
            environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
                    deduceEnvironmentClass());
        }
        ConfigurationPropertySources.attach(environment);
        return environment;
    }

到此,環(huán)境準(zhǔn)備完成。
總結(jié)代碼,環(huán)境準(zhǔn)備主要做了如下幾件事情:
1.確定active環(huán)境。
2.確定環(huán)境參數(shù),jvm參數(shù)及os參數(shù)。
3.加載properties,yml配置文件。
4.確定spring.main配置。

configureIgnoreBeanInfo

這里設(shè)置spring.beaninfo.ignore的值,若沒有指定,則設(shè)置為true。具體用處,有待進一步走讀代碼

printBanner

這一步是打印banner圖,即


springboot banner圖

接下來,真正進入springboot的重點部分了,跟spring真正結(jié)合的地方來了。
即如下代碼

//創(chuàng)建spring context
context = createApplicationContext();
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//【重點中的重點】調(diào)用spring的refresh方法,進行spring的bean的加載。
refreshContext(context);

下一篇我們將詳細(xì)介紹spring的context的初始化。這里需要對spring的源碼及原理有一些了解。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan閱讀 4,493評論 2 7
  • http://liuxing.info/2017/06/30/Spring%20AMQP%E4%B8%AD%E6%...
    sherlock_6981閱讀 16,208評論 2 11
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,248評論 0 4
  • Lua 5.1 參考手冊 by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 14,251評論 0 38
  • 夢想,每個人都有。我也不例外,高中時我想做個老師,到了大學(xué)我想做同聲翻譯,到大學(xué)畢業(yè)時我想做一個翻譯家,把好作...
    薇薇182閱讀 117評論 0 0

友情鏈接更多精彩內(nèi)容