Springboot啓動原理

 

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 <T> Collection<T> getSpringFactoriesInstances(Class<T> 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<T> 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簡述react

1 StackTrace用棧的形式保存了方法的調用信息.web

2 怎麼獲取這些調用信息呢?spring

可用Thread.currentThread().getStackTrace()方法獲得當前線程的StackTrace信息.該方法返回的是一個StackTraceElement數組.數據庫

3 該StackTraceElement數組就是StackTrace中的內容.數組

4 遍歷該StackTraceElement數組.就能夠看到方法間的調用流程.springboot

好比線程中methodA調用了methodB那麼methodA先入棧methodB再入棧.服務器

5 在StackTraceElement數組下標爲2的元素中保存了當前方法的所屬文件名,當前方法所屬的類名,以及該方法的名字app

除此之外還能夠獲取方法調用的行數.less

6 在StackTraceElement數組下標爲3的元素中保存了當前方法的調用者的信息和它調用時的代碼行數.ide

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<SpringBootExceptionReporter> 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);
    }
}

 

@Componentpublic class TestCommandLineRunn implements CommandLineRunner {    @Override    public void run(String... args) throws Exception {        System.out.println("TestCommandLineRunn.runt\t--->"+ Arrays.toString(args));    }}
相關文章
相關標籤/搜索