SpringBoot2.0 run方法分析和执行过程

SpringBoot为何如此简单? 他到底做了什么? 让一个项目启动如此简单?这次我们简单看看spring为我们做了什么
以下是springboot项目启动方法

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

这里是关键核心代码

/**
	 * Run the Spring application, creating and refreshing a new
	 * {@link ApplicationContext}.
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return a running {@link ApplicationContext}
	 */
	public ConfigurableApplicationContext run(String... args) {
		//1 统计埋点
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		//2 默认启用Headless模式(Headless模式是在缺少显示屏、键盘或者鼠标时的系统配置)
		configureHeadlessProperty();
		//3 启动SpringApplicationRunListener 监听器
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			//4 配置运行环境
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
					args);
			//解析命令行参数		
			ConfigurableEnvironment environment = prepareEnvironment(listeners,
					applicationArguments);
			configureIgnoreBeanInfo(environment);
			// 5 获取Banner
			Banner printedBanner = printBanner(environment);
			// 6 创建ApplicationContext 
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(
					SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);
			// 7 刷新IOC容器		
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass)
						.logStarted(getApplicationLog(), stopWatch);
			}
			// 8 发布ApplicationStartedEvent 事件
			listeners.started(context);
			// 9 启动所有ApplicationRunner 和 CommandLineRunner方法
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
			// 发布ApplicationReadyEvent事件
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

这是spring run 方法启动项目中所有执行的情况
主要总结为以下几个步骤
1 创建启动监听时间
2 启动SpringApplicationRunListener 监听器
3 解析并配置运行环境
4 创建IOC 容器,刷新IOC容器
5 启动所有 ApplicationRunner 和 CommandLineRunner

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值