天天看點

SpringBoot應用啟動過程分析

一.應用啟動類

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
           

開發SpirngBoot應用時,入口類就這簡單的幾行。但是卻完成了N多服務的初始化、加載和釋出。那麼這幾行代碼究竟幹了什麼呢,SpringBoot應用到底是怎麼啟動的。

二[email protected]注解

2.1.SpringBootApplication注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
           

@[email protected][email protected][email protected]

[email protected]

/**
 * Indicates that a class Spring Boot application
 * {@link Configuration @Configuration}. Can be used as an alternative to the Spring's
 * standard {@code @Configuration} annotation so that configuration can be found
 * automatically (for example in tests).
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}
           

SpringBootConfiguration注解和Spring的@Configuration注解作用一樣。标注目前類是配置類,并會将目前類内聲明的一個或多個以@Bean注解标記的方法的執行個體納入到spring容器中。比如容器加載時,會生成Hello的Bean加載到IOC容器中。

@SpringBootConfiguration
public class ExampleConfig {
    @Bean
    public void Hello(){
        System.out.println("hello");
    }
}
           

[email protected]

@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

}
           

這個注解是SpringBoot能進行自動配置的關鍵。@Import注解用于導入配置類,我們看下導入類EnableAutoConfigurationImportSelector。容器重新整理時,會調用AutoConfigurationImportSelector類的selectImports方法,掃描META-INF/spring.factories檔案自動配置類(key為EnableAutoConfiguration),然後Spring容器處理配置類。(對Spring的一些加載過程不清晰,我是相當的迷啊)

[email protected]

@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
/**
 * Configures component scanning directives for use with @{@link Configuration} classes.
 * Provides support parallel with Spring XML's {@code <context:component-scan>} element.
 *
 * <p>Either {@link #basePackageClasses} or {@link #basePackages} (or its alias
 * {@link #value}) may be specified to define specific packages to scan. If specific
 * packages are not defined, scanning will occur from the package of the
 * class that declares this annotation.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan
           

@ComponentScan掃描指定的包路徑,若未指定包路徑,則以聲明這個注解的類作為基本包路徑。比如@SpringBootApplication就沒有指定包路徑,則DemoApplication的包路徑将作為掃描的基本包路徑,是以強烈建議将主類放在頂層目錄下。

excludeFilters屬性指定哪些類型不符合元件掃描的條件,會在掃描的時候過濾掉。

@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)
           

比如上面這段代碼。@Filter聲明了過濾器類型類為自定義類型(需要實作TypeFilter接口),過濾器為AutoConfigurationExcludeFilter。當match方法為true,傳回掃描類對象,否則過濾掉。但是要注意@ComponentScan的key為excludeFilters,是以這些類型将在包掃描的時候過濾掉,也就是說,ComponentScan在掃描時,發現目前掃描類滿足macth的條件(match傳回true),是不會将該類加載到容器的。

//metadataReader  表示讀取到的目前正在掃描的類的資訊
    //metadataReaderFactory 表示可以獲得到其他任何類的資訊
    @Override
    public boolean match(MetadataReader metadataReader,
            MetadataReaderFactory metadataReaderFactory) throws IOException {
        return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader);
    }
    //該類是帶有Configuration注解的配置類
    private boolean isConfiguration(MetadataReader metadataReader) {
        return metadataReader.getAnnotationMetadata()
                .isAnnotated(Configuration.class.getName());
    }
    //該類是否為spring.factory配置的自動配置類
    private boolean isAutoConfiguration(MetadataReader metadataReader) {
        return getAutoConfigurations()
                .contains(metadataReader.getClassMetadata().getClassName());
    }
           

三.run(DemoApplication.class, args)解析

3.1.進入SpringApplication

public static ConfigurableApplicationContext run(Class<?>[] primarySources,
      String[] args) {
   return new SpringApplication(primarySources).run(args);
}
           

我們根據DemoApplication跟進代碼,發現其調用的SpringApplication類的run方法。這個方法就幹了2件事:一是建立SpringApplication對象,二是啟動SpringApplication。

3.2.SpringApplication構造器分析

1.構造器

public SpringApplication(Class<?>... primarySources) {
    this(null, primarySources);
}
/**
* Create a new {@link SpringApplication} instance. The application context will load
* beans from the specified primary sources
*/
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應用,servlet類型web應用和非web應用,在後面用于确定執行個體化applicationContext的類型
   this.webApplicationType = WebApplicationType.deduceFromClasspath();
   //設定初始化器,讀取spring.factories檔案key ApplicationContextInitializer對應的value并執行個體化
   //ApplicationContextInitializer接口用于在Spring上下文被重新整理之前進行初始化的操作
   setInitializers((Collection) getSpringFactoriesInstances(
         ApplicationContextInitializer.class));

   //設定監聽器,讀取spring.factories檔案key ApplicationListener對應的value并執行個體化
   // interface ApplicationListener<E extends ApplicationEvent> extends EventListener
   //ApplicationListener繼承EventListener,實作了觀察者模式。對于Spring架構的觀察者模式實作,它限定感興趣的事件類型需要是ApplicationEvent類型事件

   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
   //沒啥特别作用,僅用于擷取入口類class對象
   this.mainApplicationClass = deduceMainApplicationClass();
}
           

在構造器裡主要幹了2件事,一個設定初始化器,二是設定監聽器。

2.設定初始化器

setInitializers((Collection) getSpringFactoriesInstances(
      ApplicationContextInitializer.class));
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
   return getSpringFactoriesInstances(type, new Class<?>[] {});
}

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
      Class<?>[] parameterTypes, Object... args) {
   ClassLoader classLoader = getClassLoader();
   // Use names and ensure unique to protect against duplicates
   Set<String> names = new LinkedHashSet<>(
    //從類路徑的META-INF處讀取相應配置檔案spring.factories,然後進行周遊,讀取配置檔案中Key(type)對應的value
         SpringFactoriesLoader.loadFactoryNames(type, classLoader));
   //将names的對象執行個體化
   List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
         classLoader, args, names);
   AnnotationAwareOrderComparator.sort(instances);
   return instances;
}
           

根據入參type類型ApplicationContextInitializer.class從類路徑的META-INF處讀取相應配置檔案spring.factories并執行個體化對應Initializer。上面這2個函數後面會反複用到。

org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
           

3.設定監聽器

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
           

和設定初始化器一個套路,通過getSpringFactoriesInstances函數執行個體化監聽器。

org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener
           

3.3.run(String... args)解析

1.run函數

/**
* Run the Spring application, creating and refreshing a new ApplicationContext
*/

public ConfigurableApplicationContext run(String... args) {
   //計時器
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();

   ConfigurableApplicationContext context = null;
   Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();

   //設定java.awt.headless系統屬性為true,Headless模式是系統的一種配置模式。
   // 在該模式下,系統缺少了顯示裝置、鍵盤或滑鼠。但是伺服器生成的資料需要提供給顯示裝置等使用。
   // 是以使用headless模式,一般是在程式開始激活headless模式,告訴程式,現在你要工作在Headless        mode下,依靠系統的計算能力模拟出這些特性來
   configureHeadlessProperty();

   //擷取監聽器集合對象
   SpringApplicationRunListeners listeners = getRunListeners(args);

   //發出開始執行的事件。
   listeners.starting();

   try {
      //根據main函數傳入的參數,建立DefaultApplicationArguments對象
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(
            args);
      //根據掃描到的監聽器對象和函數傳入參數,進行環境準備。
      ConfigurableEnvironment environment = prepareEnvironment(listeners,
            applicationArguments);

      configureIgnoreBeanInfo(environment);
      Banner printedBanner = printBanner(environment);

      context = createApplicationContext();

      //和上面套路一樣,讀取spring.factories檔案key SpringBootExceptionReporter對應的value
      exceptionReporters = getSpringFactoriesInstances(
            SpringBootExceptionReporter.class,
            new Class[] { ConfigurableApplicationContext.class }, context);

      prepareContext(context, environment, listeners, applicationArguments,
            printedBanner);

      //和上面的一樣,context準備完成之後,将觸發SpringApplicationRunListener的contextPrepared執行
      refreshContext(context);

      //其實啥也沒幹。但是老版本的callRunners好像是在這裡執行的。
      afterRefresh(context, applicationArguments);

      stopWatch.stop();
      if (this.logStartupInfo) {
         new StartupInfoLogger(this.mainApplicationClass)
               .logStarted(getApplicationLog(), stopWatch);
      }
      //釋出ApplicationStartedEvent事件,發出結束執行的事件
      listeners.started(context);
      //在某些情況下,我們希望在容器bean加載完成後執行一些操作,會實作ApplicationRunner或者CommandLineRunner接口
      //後置操作,就是在容器完成重新整理後,依次調用注冊的Runners,還可以通過@Order注解設定各runner的執行順序。
      callRunners(context, applicationArguments);
   }
   catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, listeners);
      throw new IllegalStateException(ex);
   }

   try {
      listeners.running(context);
   }
   catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, null);
      throw new IllegalStateException(ex);
   }
   return context;
}
           

2.擷取run listeners

SpringApplicationRunListeners listeners = getRunListeners(args);
           

和構造器設定初始化器一個套路,根據傳入type SpringApplicationRunListener去掃描spring.factories檔案,讀取type對應的value并執行個體化。然後利用執行個體化對象建立SpringApplicationRunListeners對象。

org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener
           

EventPublishingRunListener的作用是釋出SpringApplicationEvent事件。

EventPublishingRunListener更像是被監聽對象,這個命名讓我有點迷。

public class EventPublishingRunListener implements SpringApplicationRunListener, Ordered {
    ......
   @Override
   public void starting() {
      this.initialMulticaster.multicastEvent(
            new ApplicationStartingEvent(this.application, this.args));
   }

   @Override
   public void environmentPrepared(ConfigurableEnvironment environment) {
      this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(
            this.application, this.args, environment));
   }
    ........
    
}
           

3.發出開始執行的事件

listeners.starting();
           

繼續跟進starting函數,

public void starting() {
   this.initialMulticaster.multicastEvent(
         new ApplicationStartingEvent(this.application, this.args));
}
//擷取ApplicationStartingEvent類型的事件後,釋出事件
    @Override
    public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
        ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
        for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
            Executor executor = getTaskExecutor();
            if (executor != null) {
                executor.execute(() -> invokeListener(listener, event));
            }
            else {
                invokeListener(listener, event);
            }
        }
    }
//繼續跟進invokeListener方法,最後調用ApplicationListener監聽者的onApplicationEvent處理事件
    private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
        try {
            listener.onApplicationEvent(event);
        }
        catch (ClassCastException ex) {
            .....
        }
    }
           

這個後面也會反複遇到,比如listeners.running(context)。

這裡是典型的觀察者模式。

//觀察者:監聽<E extends ApplicationEvent>類型事件
ApplicationListener<E extends ApplicationEvent> extends EventListener

//事件類型:
Event extends SpringApplicationEvent  extends ApplicationEvent extends EventObject

//被觀察者:釋出事件
EventPublishingRunListener implements SpringApplicationRunListener
           

SpringApplication根據目前事件Event類型,比如ApplicationStartingEvent,查找到監聽ApplicationStartingEvent的觀察者EventPublishingRunListener,調用觀察者的onApplicationEvent處理事件。

4.環境準備

//根據main函數傳入的參數,建立DefaultApplicationArguments對象
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
      args);
//根據掃描到的listeners對象和函數傳入參數,進行環境準備。
ConfigurableEnvironment environment = prepareEnvironment(listeners,
      applicationArguments);
           

ApplicationArguments提供運作application的參數,後面會作為一個Bean注入到容器。這裡重點說下prepareEnvironment方法做了些什麼。

private ConfigurableEnvironment prepareEnvironment(
      SpringApplicationRunListeners listeners,
      ApplicationArguments applicationArguments) {

   // Create and configure the environment
   ConfigurableEnvironment environment = getOrCreateEnvironment();

   configureEnvironment(environment, applicationArguments.getSourceArgs());

    //和listeners.starting一樣的流程
   listeners.environmentPrepared(environment);

   //上述完成了環境的建立和配置,傳入的參數和資源加載到environment

   //綁定環境到SpringApplication
   bindToSpringApplication(environment);
   if (!this.isCustomEnvironment) {
      environment = new EnvironmentConverter(getClassLoader())
            .convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
   }
   ConfigurationPropertySources.attach(environment);
   return environment;
}
           

這段代碼核心有3個。

  1. configureEnvironment,用于基本運作環境的配置。
  2. 釋出事件ApplicationEnvironmentPreparedEvent。和釋出ApplicationStartingEvent事件的流程一樣。
  3. 綁定環境到SpringApplication

5.建立ApplicationContext

context = createApplicationContext();
           

傳說中的IOC容器終于來了。

在執行個體化context之前,首先需要确定context的類型,這個是根據應用類型确定的。應用類型webApplicationType在構造器已經推斷出來了。

protected ConfigurableApplicationContext createApplicationContext() {
   Class<?> contextClass = this.applicationContextClass;
   if (contextClass == null) {
      try {
         switch (this.webApplicationType) {
         case SERVLET:
            //應用為servlet類型的web應用
            contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
            break;
         case REACTIVE:
            //應用為響應式web應用
            contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
            break;
         default:
            //應用為非web類型的應用
            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);
}
           

擷取context類型後,進行執行個體化,這裡根據class類型擷取無參構造器進行執行個體化。

public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException {
   Assert.notNull(clazz, "Class must not be null");
   if (clazz.isInterface()) {
      throw new BeanInstantiationException(clazz, "Specified class is an interface");
   }
   try {
       //clazz.getDeclaredConstructor()擷取無參的構造器,然後進行執行個體化
      return instantiateClass(clazz.getDeclaredConstructor());
   }
   catch (NoSuchMethodException ex) {
    .......
}
           

比如web類型為servlet類型,就會執行個體化org.springframework.boot.web.servlet.context.

AnnotationConfigServletWebServerApplicationContext類型的context。

6.context前置處理階段

private void prepareContext(ConfigurableApplicationContext context,
      ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
      ApplicationArguments applicationArguments, Banner printedBanner) {
   //關聯環境
   context.setEnvironment(environment);

   //ApplicationContext預處理,主要配置Bean生成器以及資源加載器
   postProcessApplicationContext(context);
    
   //調用初始化器,執行initialize方法,前面set的初始化器終于用上了
   applyInitializers(context);
   //釋出contextPrepared事件,和釋出starting事件一樣,不多說
   listeners.contextPrepared(context);
   if (this.logStartupInfo) {
      logStartupInfo(context.getParent() == null);
      logStartupProfileInfo(context);
   }

   // Add boot specific singleton beans
   ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
   //bean, springApplicationArguments,用于擷取啟動application所需的參數
   beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
    
   //加載列印Banner的Bean
   if (printedBanner != null) {
      beanFactory.registerSingleton("springBootBanner", printedBanner);
   }
   
   if (beanFactory instanceof DefaultListableBeanFactory) {
      ((DefaultListableBeanFactory) beanFactory)
            .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
   }
   // Load the sources,根據primarySources加載resource。primarySources:一般為主類的class對象
   Set<Object> sources = getAllSources();
   Assert.notEmpty(sources, "Sources must not be empty");
   //構造BeanDefinitionLoader并完成定義的Bean的加載
   load(context, sources.toArray(new Object[0]));
   //釋出ApplicationPreparedEvent事件,表示application已準備完成
   listeners.contextLoaded(context);
}
           

7.重新整理容器

private void refreshContext(ConfigurableApplicationContext context) {
   refresh(context);
   // 注冊一個關閉容器時的鈎子函數,在jvm關閉時調用
   if (this.registerShutdownHook) {
      try {
         context.registerShutdownHook();
      }
      catch (AccessControlException ex) {
         // Not allowed in some environments.
      }
   }
}
           

調用父類AbstractApplicationContext重新整理容器的操作,具體的還沒看。

@Override
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();
      }
       ......
}
           

8.後置操作,調用Runners

後置操作,就是在容器完成重新整理後,依次調用注冊的Runners,還可以通過@Order注解設定各runner的執行順序。

Runner可以通過實作ApplicationRunner或者CommandLineRunner接口。

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

根據源碼可知,runners收集從容器擷取的ApplicationRunner和CommandLineRunner類型的Bean,然後依次執行。

9.釋出ApplicationReadyEvent事件

listeners.running(context);
           

應用啟動完成,可以對外提供服務了,在這裡釋出ApplicationReadyEvent事件。流程還是和starting時一樣。

繼續閱讀