Spring boot啓動流程

            Spring Boot的代碼main方法啓動爲例子分析

        SpringApplication.run方法java

public static ConfigurableApplicationContext run(Object source, String... args) {
		return run(new Object[] { source }, args);
	}

public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
		return new SpringApplication(sources).run(args);
	}

 

進而可知又從新建立了個一個SpringApplication類後,執行run方法web

在建立SpringApplication這個類時候的用到了initialize方法spring

 

private void initialize(Object[] sources) {
//判斷傳入的參數,有就做爲數組保存起來
		if (sources != null && sources.length > 0) {
			this.sources.addAll(Arrays.asList(sources));
		}
//測試是不是web環境
		this.webEnvironment = deduceWebEnvironment();
//初始化spring.factories文件中對應的ApplicationContextInitializer實現類(四個)
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
//初始化spring.factories文件中對應的ApplicationListener實現類(九個)
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//經過當前堆棧找到入口main函數所在的類
		this.mainApplicationClass = deduceMainApplicationClass();
	}

 而後運行新對象的run方法數組

public ConfigurableApplicationContext run(String... args) {
//啓動監視器,記錄啓動的時間等信息
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		FailureAnalyzers analyzers = null;

//用來設置java.awt.headless 屬性是true 仍是false, java.awt.headless是J2SE的一種模式用於在缺乏顯示屏、鍵盤或者鼠標時的系統配置,不少監控工具如jconsole 須要將該值設置爲true

		configureHeadlessProperty();
//根據spring.factories文件獲取到SpringApplicationRunListeners 的實現類名org.springframework.boot.context.event.EventPublishingRunListener
實例化,他就是一個事件發佈者,內部持有一個EventPublishingRunListener,真正發佈是這個類
		SpringApplicationRunListeners listeners = getRunListeners(args);
//發佈啓動事件給各個監聽器
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
					args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners,
					applicationArguments);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			analyzers = new FailureAnalyzers(context);
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			listeners.finished(context, null);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass)
						.logStarted(getApplicationLog(), stopWatch);
			}
			return context;
		}
		catch (Throwable ex) {
			handleRunFailure(context, listeners, analyzers, ex);
			throw new IllegalStateException(ex);
		}
	}
相關文章
相關標籤/搜索