在上篇文章:SpringBoot源码解析:创建SpringApplication对象实例中,我们详细描述了SpringApplication对象实例的创建过程,本篇文章继续看run方法的执行逻辑吧

  1. public ConfigurableApplicationContext run(String... args) {
  2. StopWatch stopWatch = new StopWatch();
  3. stopWatch.start();
  4. ConfigurableApplicationContext context = null;
  5. Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
  6. configureHeadlessProperty();
  7. SpringApplicationRunListeners listeners = getRunListeners(args);
  8. listeners.starting();
  9. try {
  10. ApplicationArguments applicationArguments = new DefaultApplicationArguments(
  11. args);
  12. ConfigurableEnvironment environment = prepareEnvironment(listeners,
  13. applicationArguments);
  14. //后面还有,本篇文章就解析到这。。。。
  15. }
  1. 第一行使用了StopWatch来记录开始时间
  2. 设置了java.awt.headless环境变量,在网上了解了一下这个变量的相关信息

Headless模式是系统的一种配置模式。在系统可能缺少显示设备、键盘或鼠标这些外设的情况下可以使用该模式

个人理解为是一些图形相关的组件能否使用的开关,欢迎各位大佬指正

  1. 接着遍历所有构造SpringApplication实例时加载的SpringApplicationRunListener,调用它们的started方法

这里构造时仅仅加载了一个EventPublishingRunListener类,所以咱们就来解析一下这个东东

  1. public void starting() {
  2. this.initialMulticaster.multicastEvent(
  3. new ApplicationStartingEvent(this.application, this.args));
  4. }

可以看到这里调用了SimpleApplicationEventMulticaster类的multicastEvent方法并且传入了ApplicationStartingEvent对象,看名字就知道了这个是SpringBoot启动事件

  1. public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
  2. ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
  3. for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
  4. Executor executor = getTaskExecutor();
  5. if (executor != null) {
  6. executor.execute(() -> invokeListener(listener, event));
  7. }
  8. else {
  9. invokeListener(listener, event);
  10. }
  11. }
  12. }

其中获取监听器使用的是getApplicationListeners方法,这个方法中主要就是从最启动时获取的所有监听器和这个事件做了下匹配,返回通过匹配的监听器集合

接着就是看是否设置线程池参数,如果有线程池则使用线程池的线程进行操作,否则将同步调用监听器

  1. 把所有的命令行启动参数封装成ConfigurableEnvironment对象
  2. 准备运行时环境
  1. private ConfigurableEnvironment prepareEnvironment(
  2. SpringApplicationRunListeners listeners,
  3. ApplicationArguments applicationArguments) {
  4. ConfigurableEnvironment environment = getOrCreateEnvironment();
  5. configureEnvironment(environment, applicationArguments.getSourceArgs());
  6. listeners.environmentPrepared(environment);
  7. if (!this.webEnvironment) {
  8. environment = new EnvironmentConverter(getClassLoader())
  9. .convertToStandardEnvironmentIfNecessary(environment);
  10. }
  11. return environment;
  12. }

获取或创建环境getOrCreateEnvironment

方法名就很直观,有就直接获取,没有就新建

  1. private ConfigurableEnvironment getOrCreateEnvironment() {
  2. if (this.environment != null) {
  3. return this.environment;
  4. }
  5. if (this.webApplicationType == WebApplicationType.SERVLET) {
  6. return new StandardServletEnvironment();
  7. }
  8. return new StandardEnvironment();
  9. }

上篇文章中说过了,咱们是Servlet环境,所以当前方法是返回一个StandardServletEnvironment对象,这个对象的构造过程中调用了customizePropertySources`方法(它父类的父类调用的)

  1. protected void customizePropertySources(MutablePropertySources propertySources) {
  2. propertySources.addLast(new StubPropertySource("servletConfigInitParams"));
  3. propertySources.addLast(new StubPropertySource("servletContextInitParams"));
  4. if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {
  5. propertySources.addLast(new JndiPropertySource("jndiProperties"));
  6. }
  7. super.customizePropertySources(propertySources);
  8. }
  9. //这是它父类的
  10. protected void customizePropertySources(MutablePropertySources propertySources) {
  11. propertySources.addLast(new MapPropertySource("systemProperties", getSystemProperties()));
  12. propertySources.addLast(new SystemEnvironmentPropertySource("systemEnvironment", getSystemEnvironment()));
  13. }

可以看出StandardServletEnvironmentpropertySources中添加了两个StubPropertySource对象,而它的父类添加了一个包含java系统属性和一个操作系统环境变量的对象

配置 configureEnvironment

  1. protected void configureEnvironment(ConfigurableEnvironment environment,
  2. String[] args) {
  3. // 配置PropertySources
  4. configurePropertySources(environment, args);
  5. // 配置Profiles
  6. configureProfiles(environment, args);
  7. }

分别看一下两个方法

配置PropertySources

  1. protected void configurePropertySources(ConfigurableEnvironment environment,
  2. String[] args) {
  3. MutablePropertySources sources = environment.getPropertySources();
  4. if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
  5. // 存在默认配置将其放到最后位置
  6. sources.addLast(
  7. new MapPropertySource("defaultProperties", this.defaultProperties));
  8. }
  9. // 如果存在命令行参数则将原有的替换掉
  10. if (this.addCommandLineProperties && args.length > 0) {
  11. String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
  12. if (sources.contains(name)) {
  13. PropertySource<?> source = sources.get(name);
  14. CompositePropertySource composite = new CompositePropertySource(name);
  15. composite.addPropertySource(new SimpleCommandLinePropertySource(
  16. "springApplicationCommandLineArgs", args));
  17. composite.addPropertySource(source);
  18. sources.replace(name, composite);
  19. }
  20. else {
  21. // 将其放到第一位置
  22. sources.addFirst(new SimpleCommandLinePropertySource(args));
  23. }
  24. }
  25. }

这里就体现出了这个命令行参数比应用配置文件的优先级高的情况了

配置Profiles

从PropertySources中查找spring.profiles.active属性,存在则将其值添加activeProfiles集合中

  1. protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
  2. environment.getActiveProfiles();
  3. Set<String> profiles = new LinkedHashSet<>(this.additionalProfiles);
  4. profiles.addAll(Arrays.asList(environment.getActiveProfiles()));
  5. environment.setActiveProfiles(StringUtils.toStringArray(profiles));
  6. }

发布EnvirongmentPreparedEvent事件

绑定环境

  1. protected void bindToSpringApplication(ConfigurableEnvironment environment) {
  2. try {
  3. Binder.get(environment).bind("spring.main", Bindable.ofInstance(this));
  4. }
  5. catch (Exception ex) {
  6. throw new IllegalStateException("Cannot bind to SpringApplication", ex);
  7. }
  8. }

转换环境

如果web环境变更为NONE则将StandardServletEnvironment转换为StandardEnvironment

ConfigurationPropertySources.attach(environment)

  1. public static void attach(Environment environment) {
  2. Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
  3. MutablePropertySources sources = ((ConfigurableEnvironment) environment)
  4. .getPropertySources();
  5. PropertySource<?> attached = sources.get("configurationProperties");
  6. if (attached != null && attached.getSource() != sources) {
  7. sources.remove("configurationProperties");
  8. attached = null;
  9. }
  10. if (attached == null) {
  11. sources.addFirst(new ConfigurationPropertySourcesPropertySource(
  12. "configurationProperties",
  13. new SpringConfigurationPropertySources(sources)));
  14. }
  15. }

最终这个sources对象的第一个位置放的是它自己,循环引用,这个具体的含义还有待挖掘

继续分析run()方法

  1. public ConfigurableApplicationContext run(String... args) {
  2. //。。。
  3. //接上文继续
  4. configureIgnoreBeanInfo(environment);
  5. Banner printedBanner = printBanner(environment);
  6. context = createApplicationContext();
  7. exceptionReporters = getSpringFactoriesInstances(
  8. SpringBootExceptionReporter.class,
  9. new Class[] { ConfigurableApplicationContext.class }, context);
  10. prepareContext(context, environment, listeners, applicationArguments,
  11. printedBanner);
  12. refreshContext(context);
  13. afterRefresh(context, applicationArguments);
  14. stopWatch.stop();
  15. if (this.logStartupInfo) {
  16. new StartupInfoLogger(this.mainApplicationClass)
  17. .logStarted(getApplicationLog(), stopWatch);
  18. }
  19. listeners.started(context);
  20. callRunners(context, applicationArguments);
  21. }
  22. catch (Throwable ex) {
  23. handleRunFailure(context, listeners, exceptionReporters, ex);
  24. throw new IllegalStateException(ex);
  25. }
  26. listeners.running(context);
  27. return context;
  28. }
  1. 获取系统属性spring.beaninfo.ignore
  1. private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
  2. if (System.getProperty(
  3. CachedIntrospectionResults."spring.beaninfo.ignore") == null) {
  4. Boolean ignore = environment.getProperty("spring.beaninfo.ignore",
  5. Boolean.class, Boolean.TRUE);
  6. System.setProperty(CachedIntrospectionResults."spring.beaninfo.ignore",
  7. ignore.toString());
  8. }
  9. }

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

  1. 打印banner
  2. 根据当前环境创建ApplicationContext
  1. protected ConfigurableApplicationContext createApplicationContext() {
  2. Class<?> contextClass = this.applicationContextClass;
  3. if (contextClass == null) {
  4. try {
  5. switch (this.webApplicationType) {
  6. case SERVLET:
  7. contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
  8. break;
  9. case REACTIVE:
  10. contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
  11. break;
  12. default:
  13. contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
  14. }
  15. }
  16. catch (ClassNotFoundException ex) {
  17. throw new IllegalStateException(
  18. "Unable create a default ApplicationContext, "
  19. + "please specify an ApplicationContextClass",
  20. ex);
  21. }
  22. }
  23. return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
  24. }

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

  1. 加载SpringBootExceptionReporter,这个类里包含了SpringBoot启动失败后异常处理相关的组件
  1. private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
  2. Class<?>[] parameterTypes, Object... args) {
  3. ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  4. Set<String> names = new LinkedHashSet<>(
  5. SpringFactoriesLoader.loadFactoryNames(type, classLoader));
  6. List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
  7. classLoader, args, names);
  8. AnnotationAwareOrderComparator.sort(instances);
  9. return instances;
  10. }
  1. prepareContext 这一块还是比较长的
  1. private void prepareContext(ConfigurableApplicationContext context,
  2. ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
  3. ApplicationArguments applicationArguments, Banner printedBanner) {
  4. context.setEnvironment(environment);
  5. postProcessApplicationContext(context);
  6. applyInitializers(context);
  7. listeners.contextPrepared(context);
  8. if (this.logStartupInfo) {
  9. logStartupInfo(context.getParent() == null);
  10. logStartupProfileInfo(context);
  11. }
  12. context.getBeanFactory().registerSingleton("springApplicationArguments",
  13. applicationArguments);
  14. if (printedBanner != null) {
  15. context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
  16. }
  17. // Load the sources
  18. Set<Object> sources = getAllSources();
  19. Assert.notEmpty(sources, "Sources must not be empty");
  20. load(context, sources.toArray(new Object[0]));
  21. listeners.contextLoaded(context);
  22. }

    1. 第一行,将context中相关的environment全部替换
  1. public void setEnvironment(ConfigurableEnvironment environment) {
  2. super.setEnvironment(environment); // 设置context的environment
  3. this.reader.setEnvironment(environment); // 实例化context的reader属性的conditionEvaluator属性
  4. this.scanner.setEnvironment(environment); // 设置context的scanner属性的environment属性
  5. }

    1. 上下文后处理
  1. protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
  2. if (this.beanNameGenerator != null) {
  3. context.getBeanFactory().registerSingleton(
  4. AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
  5. this.beanNameGenerator);
  6. }
  7. if (this.resourceLoader != null) {
  8. if (context instanceof GenericApplicationContext) {
  9. ((GenericApplicationContext) context)
  10. .setResourceLoader(this.resourceLoader);
  11. }
  12. if (context instanceof DefaultResourceLoader) {
  13. ((DefaultResourceLoader) context)
  14. .setClassLoader(this.resourceLoader.getClassLoader());
  15. }
  16. }
  17. }

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


    1. 执行所有的ApplicationContextInitializerinitialize方
  1. protected void applyInitializers(ConfigurableApplicationContext context) {
  2. for (ApplicationContextInitializer initializer : getInitializers()) {
  3. Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
  4. initializer.getClass(), ApplicationContextInitializer.class);
  5. Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
  6. initializer.initialize(context);
  7. }
  8. }

    1. listeners.contextPrepared(context)这是个空方法,没有实现,一个Spring的扩展点

    1. 打印profile

    1. 注册bean:springApplicationArguments

    1. 发布事件
  1. public void contextLoaded(ConfigurableApplicationContext context) {
  2. for (ApplicationListener<?> listener : this.application.getListeners()) {
  3. if (listener instanceof ApplicationContextAware) {
  4. ((ApplicationContextAware) listener).setApplicationContext(context);
  5. }
  6. context.addApplicationListener(listener);
  7. }
  8. this.initialMulticaster.multicastEvent(
  9. new ApplicationPreparedEvent(this.application, this.args, context));
  10. }

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


    1. load,其实就是创建了一个BeanDefinitionLoader对象
  1. protected void load(ApplicationContext context, Object[] sources) {
  2. if (logger.isDebugEnabled()) {
  3. logger.debug(
  4. "Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
  5. }
  6. BeanDefinitionLoader loader = createBeanDefinitionLoader(
  7. getBeanDefinitionRegistry(context), sources);
  8. if (this.beanNameGenerator != null) {
  9. loader.setBeanNameGenerator(this.beanNameGenerator);
  10. }
  11. if (this.resourceLoader != null) {
  12. loader.setResourceLoader(this.resourceLoader);
  13. }
  14. if (this.environment != null) {
  15. loader.setEnvironment(this.environment);
  16. }
  17. loader.load();
  18. }
  1. 容器的初始化refreshContext
    这个方法最后还是调用的AbstractApplicationContext类的refresh方法,由于篇幅过长这里就不展开了,感兴趣的同学可以参考这篇文章:基于注解的SpringIOC源码解析
  1. public void refresh() throws BeansException, IllegalStateException {
  2. synchronized (this.startupShutdownMonitor) {
  3. // 记录容器的启动时间、标记“已启动”状态、检查环境变量
  4. prepareRefresh();
  5. // 初始化BeanFactory容器、注册BeanDefinition
  6. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  7. // 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean
  8. prepareBeanFactory(beanFactory);
  9. try {
  10. // 扩展点
  11. postProcessBeanFactory(beanFactory);
  12. // 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法
  13. invokeBeanFactoryPostProcessors(beanFactory);
  14. // 注册 BeanPostProcessor 的实现类
  15. registerBeanPostProcessors(beanFactory);
  16. // 初始化MessageSource
  17. initMessageSource();
  18. // 初始化事件广播器
  19. initApplicationEventMulticaster();
  20. // 扩展点
  21. onRefresh();
  22. // 注册事件监听器
  23. registerListeners();
  24. // 初始化所有的 singleton beans
  25. finishBeanFactoryInitialization(beanFactory);
  26. // 广播事件
  27. finishRefresh();
  28. }
  29. catch (BeansException ex) {
  30. if (logger.isWarnEnabled()) {
  31. logger.warn("Exception encountered during context initialization - " +
  32. "cancelling refresh attempt: " + ex);
  33. }
  34. // 销毁已经初始化的的Bean
  35. destroyBeans();
  36. // 设置 'active' 状态
  37. cancelRefresh(ex);
  38. throw ex;
  39. }
  40. finally {
  41. // 清除缓存
  42. resetCommonCaches();
  43. }
  44. }
  45. }
  1. afterRefresh
    这里没有任何实现,Spring留给我们的扩展点
  2. 停止之前启动的计时装置,然后发送ApplicationStartedEvent事件
  3. 调用系统中ApplicationRunner以及CommandLineRunner接口的实现类,关于这两个接口的使用可以参考我的这篇文章:Java项目启动时执行指定方法的几种方式
  1. private void callRunners(ApplicationContext context, ApplicationArguments args) {
  2. List<Object> runners = new ArrayList<>();
  3. runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
  4. runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
  5. AnnotationAwareOrderComparator.sort(runners);
  6. for (Object runner : new LinkedHashSet<>(runners)) {
  7. if (runner instanceof ApplicationRunner) {
  8. callRunner((ApplicationRunner) runner, args);
  9. }
  10. if (runner instanceof CommandLineRunner) {
  11. callRunner((CommandLineRunner) runner, args);
  12. }
  13. }
  14. }
  1. 异常处理
  2. 发送ApplicationReadyEvent事件