springboot啓動類源碼分析

springboot自動實現的原理

springboot主程序的功能

SpringApplication的run方法

run方法:

  1. 首先他會先開啓一個SpringApplicationRunListeners監聽器。
  2. 然後創建一個應用上下文ConfigurableApplicationContext,通過這個上下文加載應用所需的類和各種環境配置等
  3. 啓動一個應用實例

public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();//開啓監聽器
		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);
		}

		try {
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}
	

創建應用上下文

一個應用能正常運行起來得需要各種配置,從創建應用上下文ConfigurableApplicationContext的源碼裏可以找到,

其中,this.load(context,…)將調用BeanDefinitionLoader來加載應用定義的和需要的類以及各種資源.

//注意:新版本中有變動
context = createApplicationContext();

自動加載

在BeanDefinitionLoader中,有個load(Class<?> source)方法用來加載類定義.
其中形參source指的就是springboot主啓動程序的Application.class.

在方法裏通過
isComponent是否存在註解,有的話就調用註解相關的類定義,這樣主程序上的註解(@SpringBootApplication)將被調用

@SpringBootApplication會導入一系列自動配置的類,還會加載應用中一些自定義的類


整理一下上面的流程

上下文源碼中
加載類和資源
加載類定義
檢查是否有註解
SpringBootApplication註解
最後的最後
run方法
開啓一個監聽器
創建應用上下文
this.load
BeanDefinitionLoader
Class source
isComponent
導入加載一系列的類
啓動一個應用實例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章