1. 程式人生 > >Spring Boot 啟動應用原理

Spring Boot 啟動應用原理

1.執行run方法

public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        FailureAnalyzers analyzers = null;
        this.configureHeadlessProperty();
        //獲取SpringApplicationRunListeners;從類路徑下META-INF/spring.factories
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        //回撥所有獲取SpringApplicationRunListeners .starting()方法,starting()方法內部遍歷listener並呼叫starting()方法
        listeners.starting();

        try {
        //封裝命令列引數
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //環境準備
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            //環境準備完成後回撥SpringApplicationRunListeners.penvironmentPrepared()方法,表示環境準備完成
            Banner printedBanner = this.printBanner(environment);
            //建立ApplicationContext,決定建立web的ioc還是普通的ioc
            //contextClass = Class.forName(this.webEnvironment ? "org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext" : "org.springframework.context.annotation.AnnotationConfigApplicationContext"); 
            //createApplicationContext()內部程式碼
            context = this.createApplicationContext();
            new FailureAnalyzers(context);
            //準備上下文環境,將environment儲存到ioc中
            //回撥之前的ApplicationContextInitalize的Initialize()方法
            //回撥所有的SpringApplicationRunListener的contextLoaded()方法
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            //重新整理容器,ioc容器初始話
            this.refreshContext(context);
            //從ioc容器中獲取所有的ApplicationRunner和CommandLineRunner進行回撥
            //ApplicationRunner先回調,CommandlineRunner進行回撥
            this.afterRefresh(context, applicationArguments);
            //所有的SpringApplicationRunListener回撥finished方法
            listeners.finished(context, (Throwable)null);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }
		//整個springboot應用啟動完成後,返回ioc容器
            return context;	
        } catch (Throwable var9) {
            this.handleRunFailure(context, listeners, (FailureAnalyzers)analyzers, var9);
            throw new IllegalStateException(var9);
        }
    }