SpringApplication到底run了什么下

5次阅读

共计 8982 个字符,预计需要花费 23 分钟才能阅读完成。

我们分析了下面这个 run 方法的前半部分,本篇文章继续开工

    public ConfigurableApplicationContext run(String… args) {//。。。// 接上文继续            configureIgnoreBeanInfo(environment);            Banner printedBanner = printBanner(environment);            context= createApplicationContext();            exceptionReporters = getSpringFactoriesInstances(                    SpringBootExceptionReporter.class,                    newClass[] {ConfigurableApplicationContext.class},context);            prepareContext(context, environment, listeners, applicationArguments,                    printedBanner);            refreshContext(context);            afterRefresh(context, applicationArguments);            stopWatch.stop();            if(this.logStartupInfo) {newStartupInfoLogger(this.mainApplicationClass)                        .logStarted(getApplicationLog(), stopWatch);            }            listeners.started(context);            callRunners(context, applicationArguments);        }        catch (Throwable ex) {handleRunFailure(context, listeners, exceptionReporters, ex);            thrownewIllegalStateException(ex);        }        listeners.running(context);        returncontext;    }

  • 获取系统属性 spring.beaninfo.ignore

privatevoidconfigureIgnoreBeanInfo(ConfigurableEnvironment environment) {if(System.getProperty(                CachedIntrospectionResults.”spring.beaninfo.ignore”) ==null) {Booleanignore = environment.getProperty(“spring.beaninfo.ignore”,                    Boolean.class,Boolean.TRUE);            System.setProperty(CachedIntrospectionResults.”spring.beaninfo.ignore”,                    ignore.toString());        }    }

但是这个属性的作用还真不知道。。

  • 打印 banner
  • 根据当前环境创建 ApplicationContext

protected ConfigurableApplicationContext createApplicationContext() {        Class<?> contextClass =this.applicationContextClass;        if(contextClass ==null) {try{               switch(this.webApplicationType) {caseSERVLET:                    contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);                    break;               caseREACTIVE:                    contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);                    break;               default:                    contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);                }            }            catch(ClassNotFoundException ex) {thrownewIllegalStateException(                        “Unable create a default ApplicationContext, ”                                +”please specify an ApplicationContextClass”,                        ex);            }        }        return(ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);    }

基于咱们的 Servlet 环境,所以创建的 ApplicationContext 为 AnnotationConfigServletWebServerApplicationContext

  • 加载 SpringBootExceptionReporter,这个类里包含了 SpringBoot 启动失败后异常处理相关的组件

private<T>Collection<T> getSpringFactoriesInstances(Class<T> type,            Class<?>[] parameterTypes,Object… args) {ClassLoaderclassLoader =Thread.currentThread().getContextClassLoader();        Set<String> names =newLinkedHashSet<>(               SpringFactoriesLoader.loadFactoryNames(type, classLoader));        List<T> instances = createSpringFactoriesInstances(type, parameterTypes,                classLoader, args, names);        AnnotationAwareOrderComparator.sort(instances);        returninstances;    }

10 prepareContext 这一块还是比较长的

privatevoidprepareContext(ConfigurableApplicationContextcontext,        ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,        ApplicationArguments applicationArguments, Banner printedBanner) {context.setEnvironment(environment);    postProcessApplicationContext(context);    applyInitializers(context);    listeners.contextPrepared(context);   if(this.logStartupInfo) {logStartupInfo(context.getParent() ==null);        logStartupProfileInfo(context);    }   context.getBeanFactory().registerSingleton(“springApplicationArguments”,            applicationArguments);                                   if(printedBanner !=null) {context.getBeanFactory().registerSingleton(“springBootBanner”, printedBanner);    }   // Load the sources    Set<Object> sources = getAllSources();                         Assert.notEmpty(sources,”Sources must not be empty”);           load(context, sources.toArray(newObject[0]));    listeners.contextLoaded(context);}1. 第一行,将 context 中相关的 environment 全部替换 public void setEnvironment(ConfigurableEnvironment environment) {super.setEnvironment(environment);            // 设置 context 的 environment   this.reader.setEnvironment(environment);   // 实例化 context 的 reader 属性的 conditionEvaluator 属性   this.scanner.setEnvironment(environment);   // 设置 context 的 scanner 属性的 environment 属性 }2. 上下文后处理 protectedvoidpostProcessApplicationContext(ConfigurableApplicationContextcontext) {if(this.beanNameGenerator!=null) {context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,               this.beanNameGenerator);    }   if(this.resourceLoader!=null) {if(contextinstanceof GenericApplicationContext) {((GenericApplicationContext)context)                    .setResourceLoader(this.resourceLoader);        }        if(contextinstanceof DefaultResourceLoader) {((DefaultResourceLoader)context)                    .setClassLoader(this.resourceLoader.getClassLoader());        }    }}

这一块默认 beanNameGenerator 和 resourceLoader 都是空的,只有当我们自定义这两个对象时才会把容器内的 bean 替换
3. 执行所有的 ApplicationContextInitializer 的 initialize 方法

protectedvoidapplyInitializers(ConfigurableApplicationContextcontext) {for(ApplicationContextInitializer initializer : getInitializers()) {Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(                initializer.getClass(), ApplicationContextInitializer.class);        Assert.isInstanceOf(requiredType,context,”Unable to call initializer.”);        initializer.initialize(context);    }}4.`listeners.contextPrepared(context)` 这是个空方法,没有实现,一个 Spring 的扩展点 5. 打印 profile6. 注册 bean:`springApplicationArguments`7. 发布事件 publicvoidcontextLoaded(ConfigurableApplicationContextcontext) {for(ApplicationListener<?> listener :this.application.getListeners()) {if(listener instanceof ApplicationContextAware) {((ApplicationContextAware) listener).setApplicationContext(context);            }            context.addApplicationListener(listener);        }        this.initialMulticaster.multicastEvent(newApplicationPreparedEvent(this.application,this.args,context));    }

这里不仅发布了 ApplicationPreparedEvent 事件,还往实现了 ApplicationContextAware 接口的监听器中注入了 context 容器
8. load,其实就是创建了一个 BeanDefinitionLoader 对象

protectedvoidload(ApplicationContextcontext, Object[] sources) {if(logger.isDebugEnabled()) {logger.debug(                    “Loading source “+ StringUtils.arrayToCommaDelimitedString(sources));        }        BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources);        if(this.beanNameGenerator!=null) {loader.setBeanNameGenerator(this.beanNameGenerator);        }        if(this.resourceLoader!=null) {loader.setResourceLoader(this.resourceLoader);        }        if(this.environment!=null) {loader.setEnvironment(this.environment);        }        loader.load();}

  • 容器的初始化 refreshContext
    这个方法最后还是调用的 AbstractApplicationContext 类的 refresh 方法,由于篇幅过长这里就不展开了,感兴趣的同学可以参考这篇文章:基于注解的 SpringIOC 源码解析

public void refresh() throws BeansException, IllegalStateException {   synchronized(this.startupShutdownMonitor) {// 记录容器的启动时间、标记“已启动”状态、检查环境变量      prepareRefresh();      // 初始化 BeanFactory 容器、注册 BeanDefinition      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();      // 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean      prepareBeanFactory(beanFactory);      try{// 扩展点         postProcessBeanFactory(beanFactory);         // 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法         invokeBeanFactoryPostProcessors(beanFactory);         // 注册 BeanPostProcessor 的实现类         registerBeanPostProcessors(beanFactory);         // 初始化 MessageSource         initMessageSource();         // 初始化事件广播器         initApplicationEventMulticaster();         // 扩展点         onRefresh();         // 注册事件监听器         registerListeners();         // 初始化所有的 singleton beans         finishBeanFactoryInitialization(beanFactory);         // 广播事件         finishRefresh();}      catch(BeansException ex) {if(logger.isWarnEnabled()) {logger.warn(“Exception encountered during context initialization – “+                  “cancelling refresh attempt: “+ ex);         }         // 销毁已经初始化的的 Bean         destroyBeans();         // 设置 ‘active’ 状态         cancelRefresh(ex);         throwex;      }      finally{// 清除缓存         resetCommonCaches();      }   }}

  • afterRefresh
    这里没有任何实现,Spring 留给我们的扩展点
  • 停止之前启动的计时装置,然后发送 ApplicationStartedEvent 事件
  • 调用系统中 ApplicationRunner 以及 CommandLineRunner 接口的实现类,关于这两个接口的使用可以参考我的这篇文章:Java 项目启动时执行指定方法的几种方式

privatevoidcallRunners(ApplicationContext context, ApplicationArguments args) {List<Object> runners =newArrayList<>();        runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());        runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());        AnnotationAwareOrderComparator.sort(runners);        for(Objectrunner :newLinkedHashSet<>(runners)) {if(runnerinstanceofApplicationRunner) {callRunner((ApplicationRunner) runner, args);            }            if(runnerinstanceofCommandLineRunner) {callRunner((CommandLineRunner) runner, args);            }        }    }

  • 异常处理
  • 发送 ApplicationReadyEvent 事件
正文完
 0

SpringApplication到底run了什么下

5次阅读

共计 7658 个字符,预计需要花费 20 分钟才能阅读完成。

在上篇文章中 SpringApplication 到底 run 了什么(上)中,我们分析了下面这个 run 方法的前半部分,本篇文章继续开工

    public ConfigurableApplicationContext run(String... args) {
            //。。。// 接上文继续
            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, listeners, exceptionReporters, ex);
            throw new IllegalStateException(ex);
        }
        listeners.running(context);
        return context;
    }
  1. 获取系统属性spring.beaninfo.ignore
private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
        if (System.getProperty(CachedIntrospectionResults."spring.beaninfo.ignore") == null) {
            Boolean ignore = environment.getProperty("spring.beaninfo.ignore",
                    Boolean.class, Boolean.TRUE);
            System.setProperty(CachedIntrospectionResults."spring.beaninfo.ignore",
                    ignore.toString());
        }
    }

但是这个属性的作用还真不知道。。

  1. 打印 banner
  2. 根据当前环境创建 ApplicationContext
protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {switch (this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
                    break;
                case REACTIVE:
                    contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                    break;
                default:
                    contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
                }
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException(
                        "Unable create a default ApplicationContext,"
                                + "please specify an ApplicationContextClass",
                        ex);
            }
        }
        return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

基于咱们的 Servlet 环境,所以创建的 ApplicationContext 为AnnotationConfigServletWebServerApplicationContext

  1. 加载SpringBootExceptionReporter,这个类里包含了 SpringBoot 启动失败后异常处理相关的组件
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
            Class<?>[] parameterTypes, Object... args) {ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
                classLoader, args, names);
        AnnotationAwareOrderComparator.sort(instances);
        return instances;
    }

10 prepareContext 这一块还是比较长的

private void prepareContext(ConfigurableApplicationContext context,
        ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments, Banner printedBanner) {context.setEnvironment(environment);
    postProcessApplicationContext(context);
    applyInitializers(context);
    listeners.contextPrepared(context);
    if (this.logStartupInfo) {logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }

    context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);                               
    if (printedBanner != null) {context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
    }

    // Load the sources
    Set<Object> sources = getAllSources();                     
    Assert.notEmpty(sources, "Sources must not be empty");       
    load(context, sources.toArray(new Object[0]));
    listeners.contextLoaded(context);
}
1. 第一行,将 context 中相关的 environment 全部替换

public void setEnvironment(ConfigurableEnvironment environment) {super.setEnvironment(environment);            // 设置 context 的 environment
    this.reader.setEnvironment(environment);    // 实例化 context 的 reader 属性的 conditionEvaluator 属性
    this.scanner.setEnvironment(environment);    // 设置 context 的 scanner 属性的 environment 属性
}
2. 上下文后处理

protected void postProcessApplicationContext(ConfigurableApplicationContext context) {if (this.beanNameGenerator != null) {context.getBeanFactory().registerSingleton(
                AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
                this.beanNameGenerator);
    }
    if (this.resourceLoader != null) {if (context instanceof GenericApplicationContext) {((GenericApplicationContext) context)
                    .setResourceLoader(this.resourceLoader);
        }
        if (context instanceof DefaultResourceLoader) {((DefaultResourceLoader) context)
                    .setClassLoader(this.resourceLoader.getClassLoader());
        }
    }
}

这一块默认 beanNameGeneratorresourceLoader都是空的,只有当我们自定义这两个对象时才会把容器内的 bean 替换

3. 执行所有的 `ApplicationContextInitializer` 的 `initialize` 方法

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);
    }
}
4. `listeners.contextPrepared(context)` 这是个空方法,没有实现,一个 Spring 的扩展点
5. 打印 profile
6. 注册 bean:`springApplicationArguments`
7. 发布事件
public void contextLoaded(ConfigurableApplicationContext context) {for (ApplicationListener<?> listener : this.application.getListeners()) {if (listener instanceof ApplicationContextAware) {((ApplicationContextAware) listener).setApplicationContext(context);
            }
            context.addApplicationListener(listener);
        }
        this.initialMulticaster.multicastEvent(new ApplicationPreparedEvent(this.application, this.args, context));
    }

这里不仅发布了 ApplicationPreparedEvent 事件,还往实现了 ApplicationContextAware 接口的监听器中注入了 context 容器

8. load,其实就是创建了一个 `BeanDefinitionLoader` 对象
protected void load(ApplicationContext context, Object[] sources) {if (logger.isDebugEnabled()) {
            logger.debug("Loading source" + StringUtils.arrayToCommaDelimitedString(sources));
        }
        BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources);
        if (this.beanNameGenerator != null) {loader.setBeanNameGenerator(this.beanNameGenerator);
        }
        if (this.resourceLoader != null) {loader.setResourceLoader(this.resourceLoader);
        }
        if (this.environment != null) {loader.setEnvironment(this.environment);
        }
        loader.load();}
  1. 容器的初始化refreshContext

这个方法最后还是调用的 AbstractApplicationContext 类的 refresh 方法,由于篇幅过长这里就不展开了,感兴趣的同学可以参考这篇文章:基于注解的 SpringIOC 源码解析

public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {
      // 记录容器的启动时间、标记“已启动”状态、检查环境变量
      prepareRefresh();
      // 初始化 BeanFactory 容器、注册 BeanDefinition
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      // 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean
      prepareBeanFactory(beanFactory);
      try {
         // 扩展点
         postProcessBeanFactory(beanFactory);
         // 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法
         invokeBeanFactoryPostProcessors(beanFactory);
         // 注册 BeanPostProcessor 的实现类
         registerBeanPostProcessors(beanFactory);
         // 初始化 MessageSource
         initMessageSource();
         // 初始化事件广播器
         initApplicationEventMulticaster();
         // 扩展点
         onRefresh();
         // 注册事件监听器
         registerListeners();
         // 初始化所有的 singleton beans
         finishBeanFactoryInitialization(beanFactory);
         // 广播事件
         finishRefresh();}
      catch (BeansException ex) {if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization -" +
                  "cancelling refresh attempt:" + ex);
         }
         // 销毁已经初始化的的 Bean
         destroyBeans();
         // 设置 'active' 状态
         cancelRefresh(ex);
         throw ex;
      }
      finally {
         // 清除缓存
         resetCommonCaches();}
   }
}
  1. afterRefresh

这里没有任何实现,Spring 留给我们的扩展点

  1. 停止之前启动的计时装置,然后发送 ApplicationStartedEvent 事件
  2. 调用系统中 ApplicationRunner 以及 CommandLineRunner 接口的实现类,关于这两个接口的使用可以参考我的这篇文章:Java 项目启动时执行指定方法的几种方式
private void callRunners(ApplicationContext context, ApplicationArguments args) {List<Object> runners = new ArrayList<>();
        runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
        runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
        AnnotationAwareOrderComparator.sort(runners);
        for (Object runner : new LinkedHashSet<>(runners)) {if (runner instanceof ApplicationRunner) {callRunner((ApplicationRunner) runner, args);
            }
            if (runner instanceof CommandLineRunner) {callRunner((CommandLineRunner) runner, args);
            }
        }
    }
  1. 异常处理
  2. 发送 ApplicationReadyEvent 事件

正文完
 0