1 public ConfigurableApplicationContext run(String... args) { 2 StopWatch stopWatch = new StopWatch(); 3 stopWatch.start(); 4 ConfigurableApplicationContext context = null; 5 FailureAnalyzers analyzers = null; 6 configureHeadlessProperty();
//获取SpringApplicationRunListeners 从META-INF/spring.factories 下获取
//SpringApplicationRunListener.class 这种类型的,并且初始化 7 SpringApplicationRunListeners listeners = getRunListeners(args); //就一个EventPunlishRunListener 8 listeners.starting(); //回调所有starting方法 9 try { 10 ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); //没有参数 12 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); 14 Banner printedBanner = printBanner(environment);
//根据环境创建ioc容器 15 context = createApplicationContext(); 16 analyzers = new FailureAnalyzers(context); //异常分析报告,下面的try{}catch{}
//准备上下文环境,将环境保存到ioc容器中,applyInitializers(context); 17 prepareContext(context, environment, listeners, applicationArguments, printedBanner); 19 refreshContext(context); //刷新容器,spring执行流程 相当于所有配置进入 web应用创建tomcat 20 afterRefresh(context, applicationArguments); 21 listeners.finished(context, null); 22 stopWatch.stop(); 23 if (this.logStartupInfo) { 24 new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); 26 } 27 return context; 28 } 29 catch (Throwable ex) { 30 handleRunFailure(context, listeners, analyzers, ex); 31 throw new IllegalStateException(ex); 32 } 33 }
protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); //回调之前所有initializer.initialize() } }