1. 程式人生 > >十六、SpringBoot之啟動原理

十六、SpringBoot之啟動原理

幾個重要的事件回撥機制

配置在META-INF/spring.factories

    ApplicationContextInitializer
    SpringApplicationRunListener

只需要放在ioc容器中

    ApplicationRunner
    CommandLineRunner

1.啟動流程:

        public static ConfigurableApplicationContext run(Class<?>[] primarySources,
			String[] args) {
		return new SpringApplication(primarySources).run(args);
	}

2.建立SpringApplication物件

        @SuppressWarnings({ "unchecked", "rawtypes" })
	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
		this.resourceLoader = resourceLoader;
		Assert.notNull(primarySources, "PrimarySources must not be null");
                //儲存主配置類
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
                //判斷當前是否一個web應用
		this.webApplicationType = deduceWebApplicationType();
                //從類路徑下找到META-INF/spring.factories配置的所有ApplicationContextInitializer;然後儲存起來
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
                //從類路徑下找到ETA-INF/spring.factories配置的所有ApplicationListener
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
                //從多個配置類中找到有main方法的主配置類
		this.mainApplicationClass = deduceMainApplicationClass();
	}

3.執行run方法

            public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
                //聲明瞭一個IOC容器
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
                //獲取SpringApplicationRunListeners;從類路徑下META-INF/spring.factories
		SpringApplicationRunListeners listeners = getRunListeners(args);
                //回撥所有的獲取SpringApplicationRunListener.starting()方法
		listeners.starting();
		try {
                        //封裝命令列引數
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
					args);
                        //準備環境
                        //建立環境完成後回撥SpringApplicationRunListener.environmentPrepared();表示環境準備完成
			ConfigurableEnvironment environment = prepareEnvironment(listeners,
					applicationArguments);
			configureIgnoreBeanInfo(environment);
                        //列印Spring圖示
			Banner printedBanner = printBanner(environment);
                        //建立ApplicationContext;決定建立web的ioc容器還是普通的ioc容器
			context = createApplicationContext();
                        //出現異常以後,做異常分析報告的
			exceptionReporters = getSpringFactoriesInstances(
					SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
                        //準備上下文環境;將environment儲存到ioc中;而且applyInitializers();
                        //applyInitializers():回撥之前儲存的所有的ApplicationContextInitializer的initialize方法
                        //回撥所有的SpringApplicationRunListener的contextPrepared();
                        //prepareContext執行完成以後回撥所有的SpringApplicationRunListener的contextLoaded();
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);       
                        //重新整理容器;ioc容器初始化(如果是web應用還會建立嵌入式的Tomcat);
                        //掃描,建立,載入所有元件的地方;(配置類,元件,自動配置)
			refreshContext(context);
                        //從ioc容器中獲取所有的ApplicationRunner和CommandLineRunner進行回撥
                        //ApplicationRunner先回調,CommandLineRunner再回調
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass)
						.logStarted(getApplicationLog(), stopWatch);
			}
                        //所有的SpringApplicationRunListener回撥started方法
			listeners.started(context);
                        //從ioc容器中獲取所有的ApplicationRunner和CommandLineRunner進行回撥run方法
                        //ApplicationRunner先回調,CommandLineRunner再回調
			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);
		}
                //整個SpringBoot應用啟動完成以後返回啟動的ioc容器;
		return context;
	}

4.事件監聽機制

(1)配置在META-INF/spring.factories

  • ApplicationContextInitializer
//監聽IOC容器
public class HelloApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("ApplicationContextInitializer...initialize..."+applicationContext);
    }
}
  • SpringApplicationRunListener
public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {

    //必須有的構造器
    public HelloSpringApplicationRunListener(SpringApplication application, String[] args){

    }

    @Override
    public void starting() {
        System.out.println("SpringApplicationRunListener...starting...");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        Object o = environment.getSystemProperties().get("os.name");
        System.out.println("SpringApplicationRunListener...environmentPrepared.."+o);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextPrepared...");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextLoaded...");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...started..");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...running..");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("SpringApplicationRunListener...failed.."+exception);
    }

}

配置(META-INF/spring.factories)

org.springframework.context.ApplicationContextInitializer=\
com.atguigu.springboot.listener.HelloApplicationContextInitializer

org.springframework.boot.SpringApplicationRunListener=\
com.atguigu.springboot.listener.HelloSpringApplicationRunListener

(2)只需要放在ioc容器中

  • ApplicationRunner
//放在容器中
@Component
public class HelloApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner...run....");
    }
}
  • CommandLineRunner
//放在容器中
@Component
public class HelloCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner...run..."+ Arrays.asList(args));
    }
}