springboot启动分析

1.启动类,main方法可执行,传入当前类为primarySource并传入命令行参数

@SpringBootApplication
public class CmdbApp {

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

2.启动流程

public ConfigurableApplicationContext run(String... args) {
                //计时器
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
                //设置java awt headless模式,默认为true
		configureHeadlessProperty();
                //获取监听器,启动到各个生命周期都会去调用响应的方法
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
                        //解析命令行参数
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
                        //1.生成Environment,根据命令行参数配置Environment的PropertySources、Profiles、EnvironmentConverter
                        //2.绑定属性到SpringApplication
                        //3.添加ConfigurationPropertySourcesPropertySource
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
                        //根据WebApplicationType.deduceFromClasspath()创建Context, 一般为AnnotationConfigServletWebServerApplicationContext
			context = createApplicationContext();
                        //获取异常报告器具
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
                        //1.设置environment到context
                        //2.设置beanNameGenerator、classloader、resourceloader、conversionservice
                        //3.初始化ApplicationContextInitializer
                        //4.注册全局懒加载处理器
                        //5.加载BeanDefinition
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
                        //执行ConfigurableApplicationContext#refresh逻辑
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
                        //运行runners
			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;
	}
	public AnnotationConfigApplicationContext(String... basePackages) {
		this();
		scan(basePackages);
		refresh();
	}
posted @ 2022-03-06 00:08  doite  阅读(82)  评论(0)    收藏  举报