Springboot启动原理

共 18439字,需浏览 37分钟

 ·

2020-09-01 10:50

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达

  作者 |  eternal_heathens 

来源 |  urlify.cn/RFzYF3

66套java从入门到精通实战课程分享 

public static void main(String[] args) {
        //xxx.class:主配置类,(可以传多个)
        SpringApplication.run(xxx.class, args);
    }

1. 从run方法开始,创建SpringApplication,然后再调用run方法

/**
 * ConfigurableApplicationContext(可配置的应用程序上下文)
 */

public static ConfigurableApplicationContext run(Class primarySource, String... args) {
    //调用下面的run方法
    return run(new Class[]{primarySource}, args);
}

public static ConfigurableApplicationContext run(Class[] primarySources, String[] args) {
    //primarySources:主配置类
    return (new SpringApplication(primarySources)).run(args);
}

2. 创建SpringApplication

public SpringApplication(Class... primarySources) {
    //调用下面构造方法
    this((ResourceLoader) null, primarySources);
}


public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
   //获取类加载器
   this.resourceLoader = resourceLoader;
   //查看类加载器是否为空
   Assert.notNull(primarySources, "PrimarySources must not be null");
   // 保存主配置类的信息到一个哈希链表集合中,方便查询调用增删
   this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
   //获取当前应用的类型,是不是web应用,见2.1
   this.webApplicationType = WebApplicationType.deduceFromClasspath();
   //从类路径下找到META‐INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起来,见2.2
   setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
   //从类路径下找到META‐INF/spring.factories配置的所有spring.ApplicationListener;然后保存起来,原理同上
   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
   //从多个SpringApplication中找到有main方法的主SpringApplication(在调run方法的时候是可以传递多个配置类的)
   //只记录有main方法的类名,以便下一步的run
   this.mainApplicationClass = deduceMainApplicationClass();
}

2.1 deduceFromClasspath

static WebApplicationType deduceFromClasspath() {
   if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
         && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
      return WebApplicationType.REACTIVE;
   }
   for (String className : SERVLET_INDICATOR_CLASSES) {
      if (!ClassUtils.isPresent(className, null)) {
         return WebApplicationType.NONE;
      }
   }
   return WebApplicationType.SERVLET;
}

2.2 getSpringFactoriesInstances

private  Collection getSpringFactoriesInstances(Class type, Class[] parameterTypes, Object... args) {
   ClassLoader classLoader = getClassLoader();
   // Use names and ensure unique to protect against duplicates
   // 配置的所有ApplicationContextInitializer等分别到一个集合中以便查询使用,其中loadFactoryNames方法从类路径下找到META‐INF/spring.factories中传入的parameterTypes
   Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
   // 实例化传入的类
   List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
   // 排序以便提高针对他执行操作的效率
   AnnotationAwareOrderComparator.sort(instances);
   return instances;
}

2.3 deduceMainApplicationClass

private Class deduceMainApplicationClass() {
   try {
       // 查询当前的虚拟机的当前线程的StackTrace信息
      StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
      for (StackTraceElement stackTraceElement : stackTrace) {
          // 查看当前线程中已加载的类中有没有main方法
         if ("main".equals(stackTraceElement.getMethodName())) {
           //有则返回该类的类名
            return Class.forName(stackTraceElement.getClassName());
         }
      }
   }
   catch (ClassNotFoundException ex) {
      // Swallow and continue
   }
   return null;
}


StackTrace简述

1 StackTrace用栈的形式保存了方法的调用信息.

2 怎么获取这些调用信息呢?

可用Thread.currentThread().getStackTrace()方法得到当前线程的StackTrace信息.该方法返回的是一个StackTraceElement数组.

3 该StackTraceElement数组就是StackTrace中的内容.

4 遍历该StackTraceElement数组.就可以看到方法间的调用流程.

比如线程中methodA调用了methodB那么methodA先入栈methodB再入栈.

5 在StackTraceElement数组下标为2的元素中保存了当前方法的所属文件名,当前方法所属的类名,以及该方法的名字

除此以外还可以获取方法调用的行数.

6 在StackTraceElement数组下标为3的元素中保存了当前方法的调用者的信息和它调用时的代码行数.

3. 调用SpringApplication对象的run方法

public ConfigurableApplicationContext run(String... args) {
        //Simple stop watch, allowing for timing of a number of tasks, exposing totalrunning time and running time for each named task.简单来说是创建ioc容器的计时器
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        //声明IOC容器
        ConfigurableApplicationContext context = null;
        //异常报告存储列表
        Collection exceptionReporters = new ArrayList();
        //加载图形化配置
        this.configureHeadlessProperty();
        //从类路径下META‐INF/spring.factories获取SpringApplicationRunListeners,原理同2中获取ApplicationContextInitializer和ApplicationListener
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        //遍历上一步获取的所有SpringApplicationRunListener,调用其starting方法
        listeners.starting();

        Collection exceptionReporters;
        try {
            //封装命令行
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //准备环境,把上面获取到的SpringApplicationRunListeners传过去,见3.1
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            
            this.configureIgnoreBeanInfo(environment);
            //打印Banner,就是控制台那个Spring字符画
            Banner printedBanner = this.printBanner(environment);
            //根据当前环境利用反射创建IOC容器,见3.2
            context = this.createApplicationContext();
        //从类路径下META‐INF/spring.factories获取SpringBootExceptionReporter,原理同2中获取ApplicationContextInitializer和ApplicationListener
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            //准备IOC容器,见3.3
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            //刷新IOC容器,可查看配置嵌入式Servlet容器原理,所有的@Configuration和@AutoConfigutation等Bean对象全在此时加入容器中,并依据不同的选项创建了不同功能如服务器/数据库等组件。见3.4
            //可以说@SpringbootApplication中自动扫描包和Autoconfiguration也是在此时进行的
            this.refreshContext(context);
            //这是一个空方法
            this.afterRefresh(context, applicationArguments);
            //停止计时,打印时间
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }
            //调用所有SpringApplicationRunListener的started方法
            listeners.started(context);
            //见3.5 ,从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调ApplicationRunner先回调,CommandLineRunner再回调。
            this.callRunners(context, applicationArguments);
        } catch (Throwable var10) {
            this.handleRunFailure(context, var10, exceptionReporters, listeners);
            throw new IllegalStateException(var10);
        }

        try {
            //调用所有SpringApplicationRunListener的running方法
            listeners.running(context);
            //返回创建好的ioc容器,启动完成
            return context;
        } catch (Throwable var9) {
            this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
            throw new IllegalStateException(var9);
        }
    }

3.1 prepareEnvironment

private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
        //获取或者创建环境,有则获取,无则创建
        ConfigurableEnvironment environment = this.getOrCreateEnvironment();
        //配置环境
        this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
        ConfigurationPropertySources.attach((Environment)environment);
        //创建环境完成后,ApplicationContext创建前,调用前面获取的所有SpringApplicationRunListener的environmentPrepared方法,读取配置文件使之生效
        listeners.environmentPrepared((ConfigurableEnvironment)environment);
        // 环境搭建好后,需依据他改变Apllication的参数,将enviroment的信息放置到Binder中,再由Binder依据不同的条件将“spring.main”SpringApplication更改为不同的环境,为后面context的创建搭建环境
        //为什么boot要这样做,其实咱们启动一个boot的时候并不是一定只有一个Application且用main方式启动。这样子我们可以读取souces配置多的Application
        this.bindToSpringApplication((ConfigurableEnvironment)environment);
        if (!this.isCustomEnvironment) {
            environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
        }

        ConfigurationPropertySources.attach((Environment)environment);
        //回到3,将创建好的environment返回
        return (ConfigurableEnvironment)environment;
    }

3.2 createApplicationContext

protected ConfigurableApplicationContext createApplicationContext() {
        //获取当前Application中ioc容器类
        Class contextClass = this.applicationContextClass;
        //若没有则依据该应用是否为web应用而创建相应的ioc容器
        //除非为其传入applicationContext,不然Application的默认构造方法并不会创建ioc容器
        if (contextClass == null) {
            try {
                switch(this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
                    break;
                case REACTIVE:
                    contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
                    break;
                default:
                    contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
                }
            } catch (ClassNotFoundException var3) {
                throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
            }
        }
    //用bean工具类实例化ioc容器对象并返回。回到3
        return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
    }

3.3 prepareContext

private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
        //将创建好的环境放到IOC容器中
        context.setEnvironment(environment);
        //处理一些组件,没有实现postProcessA接口
        this.postProcessApplicationContext(context);
        //获取所有的ApplicationContextInitializer调用其initialize方法,这些ApplicationContextInitializer就是在2步骤中获取的,见3.3.1
        this.applyInitializers(context);
        //回调所有的SpringApplicationRunListener的contextPrepared方法,这些SpringApplicationRunListeners是在步骤3中获取的
        listeners.contextPrepared(context);

        //打印日志
        if (this.logStartupInfo) {
            this.logStartupInfo(context.getParent() == null);
            this.logStartupProfileInfo(context);
        }

        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //将一些applicationArguments注册成容器工厂中的单例对象
        beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
        if (printedBanner != null) {
            beanFactory.registerSingleton("springBootBanner", printedBanner);
        }

        if (beanFactory instanceof DefaultListableBeanFactory) {
            ((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
    
        //若是延迟加载,则在ioc容器中加入LazyInitializationBeanFactoryPostProcessor,
        if (this.lazyInitialization) {
            context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
        }

        //获取所有报告primarySources在内的所有source
        Set<Object> sources = this.getAllSources();
        Assert.notEmpty(sources, "Sources must not be empty");
        //加载容器
        this.load(context, sources.toArray(new Object[0]));
        //回调所有的SpringApplicationRunListener的contextLoaded方法
        listeners.contextLoaded(context);
    }

3.3.1 applyInitializers

protected void applyInitializers(ConfigurableApplicationContext context) {
        Iterator var2 = this.getInitializers().iterator();

        while(var2.hasNext()) {
            //将之前的所有的ApplicationContextInitializer遍历
            ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next();
            //解析查看之前从spring.factories调用的ApplicationContextInitializer是否能被ioc容器调用
            Class requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
            Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
            //可以调用则对ioc容器进行初始化(还没加载我们自己配置的bean和AutoConfiguration那些)
            initializer.initialize(context);
        }

    }//返回3.3

3.4 refreshment(context)

@Override 
//详情见内置Servlet的启动原理,最后是用ApplicationContext的实现类的refresh()方法,若是web Application则为ServletWebServerApplicationContext
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);

      try {
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory);

         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

3.5 callRunners

private void callRunners(ApplicationContext context, ApplicationArguments args) {
        List<Object> runners = new ArrayList();
        //将ioc容器中的的ApplicationRunner和CommandLineRunner(),在创建ioc容器时创建的
        runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
        runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
        AnnotationAwareOrderComparator.sort(runners);
        Iterator var4 = (new LinkedHashSet(runners)).iterator();
    
        //调用ApplicationRunner和CommandLineRunner的run方法
        while(var4.hasNext()) {
            Object runner = var4.next();
            if (runner instanceof ApplicationRunner) {
                this.callRunner((ApplicationRunner)runner, args);
            }

            if (runner instanceof CommandLineRunner) {
                this.callRunner((CommandLineRunner)runner, args);
            }
        }

    }

配置在META-INF/spring.factories

  • ApplicationContextInitializer(在我们将enviroment绑定到application后可以用来创建不同类型的context)

  • SpringApplicationRunListener(在Application 创建/运行/销毁等进行一些我们想要的特殊配置)

只需要放在ioc容器中

  • ApplicationRunner(加载没有在ApplicationContext中的bean时让bean能加载)

  • CommandLineRunner(命令行执行器)

Application初始化组件测试

1.创建ApplicationContextInitializer和SpringApplicationRunListener的实现类,并在META-INF/spring.factories文件中配置

public class TestApplicationContextInitializer implements ApplicationContextInitializer {

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        System.out.println("TestApplicationContextInitializer.initialize");
    }
}


public class TestSpringApplicationRunListener implements SpringApplicationRunListener {
    @Override
    public void starting() {
        System.out.println("TestSpringApplicationRunListener.starting");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        System.out.println("TestSpringApplicationRunListener.environmentPrepared");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("TestSpringApplicationRunListener.contextPrepared");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("TestSpringApplicationRunListener.contextLoaded");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("TestSpringApplicationRunListener.started");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("TestSpringApplicationRunListener.running");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("TestSpringApplicationRunListener.failed");
    }
}


org.springframework.context.ApplicationContextInitializer=\
cn.clboy.springbootprocess.init.TestApplicationContextInitializer

org.springframework.boot.SpringApplicationRunListener=\
cn.clboy.springbootprocess.init.TestSpringApplicationRunListener

启动报错:说是没有找到带org.springframework.boot.SpringApplication和String数组类型参数的构造器,给TestSpringApplicationRunListener添加这样的构造器

public TestSpringApplicationRunListener(SpringApplication application,String[] args) {
    }


2.创建ApplicationRunner实现类和CommandLineRunner实现类,因为是从ioc容器完成创建后中提取存放在里面的这两个Runner,因此可以直接添加到容器中,最后callRunner使用

@Component
public class TestApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunner.run\t--->"+args);
    }
}


@Component
public class TestCommandLineRunn implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("TestCommandLineRunn.runt\t--->"+ Arrays.toString(args));
    }
}



粉丝福利:108本java从入门到大神精选电子书领取

???

?长按上方锋哥微信二维码 2 秒
备注「1234」即可获取资料以及
可以进入java1234官方微信群



感谢点赞支持下哈 

浏览 61
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报