1. 程式人生 > >Spring Boot深入理解SpringApplication.run()方法啟動

Spring Boot深入理解SpringApplication.run()方法啟動

我們知道spring boot專案啟動,只需要啟動@SpringBootApplication.calss中的含有SpringApplication.run()方法的main方法就可以

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

我們下面來看看Spring Boot應用是怎麼啟動的。

SpringApplication的啟動流程

SpringApplication的啟動過程非常複雜,下面是在呼叫SpringApplication.run方法之後啟動的關鍵動作:

既然要了解原理,最直接的方式當然是看原始碼:

SpringApplication.class

public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
        this.configureHeadlessProperty();
        //初始化監聽器
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        //釋出ApplicationStartingEvent
        listeners.starting();

        try {
            //裝配引數和環境
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //釋出ApplicationEnvironmentPreparedEvent
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
            Banner printedBanner = this.printBanner(environment);
            //建立ApplicationContext,並裝配
            context = this.createApplicationContext();
            this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            //釋出ApplicationPreparedEvent
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            this.refreshContext(context);
            this.afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }
            
            //釋出ApplicationStartedEvent
            listeners.started(context);
            //執行Spring中@Bean下的一些操作,如靜態方法等
            this.callRunners(context, applicationArguments);
        } catch (Throwable var9) {
            this.handleRunFailure(context, listeners, exceptionReporters, var9);
            throw new IllegalStateException(var9);
        }

        //釋出ApplicationReadyEvent
        listeners.running(context);
        return context;
    }